I try to display data from my database, but I get 500 error page: javax.ejb.EJBException. I don't understand why it's not working. Maybe my Bean is wrong? Please help me.
Warning in Glassfish log: WARNING: WARNING: EJB5184:A system exception occurred during an invocation on EJB SearchBean, method: public java.util.Collection com.stark.logic.SearchBean.searchByNumber(int)
#Entity
#Table(name = "buy")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Buy.findAll", query = "SELECT b FROM Buy b"),
#NamedQuery(name = "Buy.findByIdBuy", query = "SELECT b FROM Buy b WHERE b.idBuy = :idBuy"),
#NamedQuery(name = "Buy.findByNumberBuy", query = "SELECT b FROM Buy b WHERE b.numberBuy = :numberBuy")})
public class Buy implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id_buy")
private Integer idBuy;
#Basic(optional = false)
#NotNull
#Column(name = "number_buy")
private int numberBuy;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "buy")
private Product product;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "buy")
private Client client;
//getters & setters
EJB BEAN:
#Stateless
#LocalBean
public class SearchBean {
#PersistenceUnit
EntityManagerFactory emf;
EntityManager em;
public Collection searchByNumber(int number){
em = emf.createEntityManager();
Query searchQuery = em.createNamedQuery("Buy.findByNumberBuy");
searchQuery.setParameter("number_buy", number);
List list = new ArrayList();
list = searchQuery.getResultList();
return list;
}
}
Servlet:
#EJB
private SearchBean searchBean;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html;charset=UTF-8");
String num = request.getParameter("number");
int number = Integer.parseInt(num);
List list = new ArrayList();
list = (List) searchBean.searchByNumber(number);
Iterator it = list.iterator();
while(it.hasNext()){
Buy buy = (Buy) it.next();
out.println(buy.getProduct());
}
}
Parameter name in #NamedQuery and in setParameter() method must be equal:
searchQuery.setParameter("numberBuy", number);
Related
#Convert(converter = MsisdnEncryptor.class,disableConversion=true)
I have used this converter in my spring boot entity class.
package com.example.demo.entity;
This is the entity class:
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
#Table(name="employee")
public class Employee {
#Id
#Column(name = "emp_id")
#SequenceGenerator(
name = "employee_sequence",
sequenceName = "employee_sequence",
allocationSize = 1
)
#GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "employee_sequence")
private Long EmpId;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "mobile_number")
**#Convert(converter = MsisdnEncryptor.class,disableConversion=true)**
**here I want to put values from application.properties in disableConversion**
private String mobileNumber;
#Column(name= "date_time")
#JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd-MM-yyyy HH:mm:ss", timezone="GMT+5:30")
private Timestamp dateTime;
}
This is the Encryptor class:
#Component
public class MsisdnEncryptor implements AttributeConverter<String, String> {
private static final Logger logger = LoggerFactory.getLogger(MsisdnEncryptor.class);
#Value("${is.enabled:true}")
private boolean isEnabled;
private static final String AES = "AES";
private static final String SECRET = "secret-key-12345";
private final Key key;
private final Cipher cipher;
public MsisdnEncryptor() throws Exception {
key = new SecretKeySpec(SECRET.getBytes(), AES);
cipher = Cipher.getInstance(AES);
}
#Override
public String convertToDatabaseColumn(String attribute) {
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
return Base64.getEncoder().encodeToString(cipher.doFinal(attribute.getBytes()));
} catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
#Override
public String convertToEntityAttribute(String dbData) {
try {
cipher.init(Cipher.DECRYPT_MODE, key);
return new String(cipher.doFinal(Base64.getDecoder().decode(dbData)));
} catch (InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
throw new IllegalStateException(e);
}
}
}
I know we can use #Value for taking the values , but it doesn't work here as it says attribute value must be constant.
Or if there is any other way of doing the encryption and enabling/disabling it from config , I would be more than happy to go through it.
I have a spring boot rest service with the following model classes -
Report class -
#Entity
#Table (name = "report")
#EntityListeners(AuditingEntityListener.class)
public class Report {
#Id
#Column (name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "from_user_id", nullable = false)
private Long fromUserId;
#Column(name = "to_user_id", nullable = false)
private Long toUserId;
#Temporal(TemporalType.DATE)
#JsonFormat(pattern = "dd-MM-yyyy hh:mm:ss")
#CreatedDate
private Date createdAt;
#Column(nullable = false)
private String observation;
[ OTHER VARS AND GETTERS AND SETTERS .... ]
}
User class -
#Entity
#Table (name = "user")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class User {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(nullable = false)
private String firstName;
#Column(nullable = false)
private String lastName;
#Column(unique = true, nullable = false)
private String email;
#Column(nullable = false)
private String password;
#OneToMany(cascade = CascadeType.ALL, targetEntity = Report.class)
#JoinColumn(name = "to_user_id")
private List<Report> reportReceivedList;
#OneToMany(cascade = CascadeType.ALL, targetEntity = Report.class)
#JoinColumn(name = "from_user_id")
private List<Report> reportSentList;
[GETTERS AND SETTERS .....]
}
This is causing a
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
which in turn is caused by
Caused by: java.sql.SQLException: Cannot add foreign key constraint
I want to create my mapping such that one user can have multiple sent reports and received reports, and once I delete a user, both sent and received reports should get deleted. I have explored loads of links for creating mappings and I am very confused because of different methods given everywhere.
i working with Spring mvc, using hibernate and JPA configuration,relation many-to-many, i'm using view technologies(jsp) test method in DAO(with controller,service) ok, when i move to writing test for DAO class , it fail, i don't know, Where am I wrong?, please could you tell me ? thanks you !
Student.java
#Entity
#Table(name = "Student")
public class Student {
#Id
#Column(name = "studentNumber", nullable = false)
private Integer studentNumber;
#Column(name = "studentName", nullable = false)
private String studentName;
#Column(name = "birthDay", nullable = false)
private String birthDay;
#Column(name = "birthPlace", nullable = false)
private String birthPlace;
#Column(name = "admissionDay", nullable = false)
private String admissionDay;
#Column(name = "score", nullable = false)
private Float score;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, mappedBy = "studentNumbers")
private Set<ClassRoom> classRooms = new HashSet<ClassRoom>();
ClassRoom.java
#Entity
#Table(name = "ClassRoom")
public class ClassRoom {
#Id
#Column(name = "classRoomID", unique = true, nullable = false)
private String classRoomID;
#Column(name = "classRoomName", nullable = false)
private String classRoomName;
#Column(name = "teacherName", nullable = false)
private String teacherName;
#JoinTable(name = "ClassRoom_Student", joinColumns = #JoinColumn(name = "classRoomID", referencedColumnName = "classRoomID", nullable = false, updatable = false) , inverseJoinColumns = #JoinColumn(name = "studentNumber", referencedColumnName = "studentNumber", nullable = false, updatable = false) )
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<Student> studentNumbers = new HashSet<Student>();
DAO class
#Repository
public class StudentDAOImpl implements StudentDAO {
#PersistenceContext(unitName = "default")
private EntityManager entityManager;
#Override
public boolean insert(Student student) {
entityManager.persist(student);
return true;
}
#Override
public boolean update(Student student) {
entityManager.merge(student);
return true;
}
#Override
public boolean delete(Integer studentNumber) {
Student student = entityManager.find(Student.class, studentNumber);
entityManager.remove(student);
return true;
}
#Override
public Student getStudentByStudentNumber(Integer studentNumber) {
Student student = entityManager.find(Student.class, studentNumber);
return student;
}
#Override
public List<Student> getAllStudent() {
return entityManager.createQuery("FROM Student").getResultList();
}
#Override
public List<String> getClassOfStudent(Integer studentNumber) {
return entityManager
.createQuery("SELECT cs.classRoomID FROM Class_Student cs WHERE cs.studentNumber=" + studentNumber)
.getResultList();
}
#Override
public boolean deleteStudentClassStudent(Integer studentNumber) {
Query query = entityManager
.createQuery("DELETE FROM ClassRoom_Student cs WHERE cs.studentNumber = " + studentNumber);
query.executeUpdate();
return true;
}}
and mockTest
#ContextConfiguration(locations = { "classpath*:applicationContext.xml" })
#RunWith(SpringJUnit4ClassRunner.class)
public class Mockito {
#Mock
private static Student studentMock;
#Mock
private static ClassRoom classMock;
#Autowired
private StudentDAO studentDAO;
#Autowired
private ClassRoomDAO classRoomDAO;
#Test
public void testCreateObject() {
assertNotNull(studentDAO);
assertNotNull(classRoomDAO);
}
#Test
public void insertTest() {
Student student = new Student(111006, "ABC", "ABC", "ABC", "ABC", 10f);
studentDAO.insert(student);
List<Student> listStudent = studentDAO.getAllStudent();
when(studentDAO.insert(student)).thenReturn(true);
assertTrue(0 == listStudent.size());
}
#Test
public void testgetStudentByStudentNumber() {
Student student = new Student();
when(studentDAO.getStudentByStudentNumber(111000002)).thenReturn(student);
assertTrue(student != null);
}
#Test
public void updateTest() {
Student student = studentDAO.getStudentByStudentNumber(111002);
student.setStudentName("new name");
student.setAdmissionDay("new Day");
student.setBirthDay("new Day");
student.setBirthPlace("new Day");
student.setScore(8f);
when(studentDAO.update(student)).thenReturn(false);
assertTrue(student == null);
}
#Test
public void deleteTest() {
when(studentDAO.delete(111005)).thenReturn(true);
Student stu = studentDAO.getStudentByStudentNumber(111005);
assertTrue(stu != null);
}
#Test
public void getAllStudentTest() {
List<Student> studentS = studentDAO.getAllStudent();
assertTrue(studentS.size() != 0);
}
#Test
public void getStudentByIdTest() {
}
}
where the error occurs
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ids.demo.dao.StudentDAO com.ids.demo.test.Mockito.studentDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ids.demo.dao.StudentDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ids.demo.dao.StudentDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1103)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:963)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 28 more
Straightforward to the point. I am given Hibernate exception Caused by: org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags.
I have 3 entities in a Parent --(1-*)--> Child --(1-*)--> Grandchild unidirectional relationship:
NetworkElement -> NetworkElementInterface -> NetworkElementInterfaceCounters
Over both relationship I have defined FetchType.LAZY.
#Entity
#Table(name = "NETWORK_ELEMENTS")
public class NetworkElement extends Device {
#Id
#Column(name = "ID_DEVICE")
private Long id;
#ManyToOne(targetEntity = DeviceLocation.class, fetch = FetchType.LAZY)
#JoinColumn(name = "ID_DEVICE_LOCATION")
private DeviceLocation deviceLocation;
#Column(name = "MODEL", length = 30)
private String model;
#Column(name = "TYPE", length = 30)
private String type;
#Column(name = "IMAGE", length = 50)
private String image;
#OneToMany(orphanRemoval = true, fetch = FetchType.LAZY, targetEntity = NetworkElementInterface.class, cascade=CascadeType.ALL)
#Size(min = 0, max = 99)
private List<NetworkElementInterface> interfaces;
}
#Entity
#Table(name = "NETWORK_ELEMENT_INTERFACES")
public class NetworkElementInterface {
#Id
#Column(name = "ID_NETWORK_ELEMENT_INTERFACES")
protected Long id;
#Column(name = "NAME")
private String name;
#Column(name = "SPEED")
private Long speed;
#Column(name = "DUPLEX")
private String duplex;
#ElementCollection(fetch = FetchType.LAZY)
#CollectionTable(name = "NETWORK_ELEMENT_INTERFACE_COUNTERS", joinColumns = #JoinColumn(name = "ID_NETWORK_ELEMENT_INTERFACE"))
#Type(type = "com.netsuite.wind.entity.NetworkElementInterfaceCounters")
private List<NetworkElementInterfaceCounters> interfaceCountersHistory;
}
#Embeddable
public class NetworkElementInterfaceCounters {
private Long inputErrors;
private Long inputDrops;
private Long inputDiscards;
private Long inputCRCErrors;
private Long inputFifoErrors;
private Long outputErros;
private Long outputDrops;
private Long outputCRCErrors;
private Long outputFifoErrors;
}
What I am trying to achieve is:
1) in my DAO to create a method which will return Parent fully populated with its children and grandchildren. (NetworkElement -> NetworkElementInterface -> NetworkElementInterfaceCounters).
1b) (not really important here, just curious) Eventually I would also like to populate children of a different type, in my NetworkElement DeviceLocation object along with populated NetworkInterfaces.
My DAO Method of NetworkElement:
#Transactional()
#SuppressWarnings("unchecked")
public NetworkElement getByIdWithInterfaces(Long id) {
final Session session = sessionFactory.getCurrentSession();
------------------------------------------------------
// This works well when I only want children to by populated
Query query = session.createQuery("SELECT ne FROM NetworkElement ne JOIN FETCH ne.interfaces WHERE ne.id = :id");
------------------------------------------------------
// This doesn't work when I also try to fetch grandchildren. I am given Hibernate exception: "cannot simultaneously fetch multiple bags"
Query query = session.createQuery("SELECT ne FROM NetworkElement ne JOIN FETCH ne.interfaces nei JOIN FETCH nei.interfaceCountersHistory WHERE ne.id = :id");
------------------------------------------------------
// Eventually I tried "FETCH ALL PROPERTIES" which also doesn't work.
Query query = session.createQuery("FROM NetworkElement ne FETCH ALL PROPERTIES WHERE ne.id = :id");
------------------------------------------------------
query.setParameter("id", id);
NetworkElement result = null;
try {
result = (NetworkElement) query.uniqueResult();
} catch (NoResultException e) {
e.printStackTrace();
}
return result;
}
So for:
1) Query query = session.createQuery("SELECT ne FROM NetworkElement ne JOIN FETCH ne.interfaces nei JOIN FETCH nei.interfaceCountersHistory WHERE ne.id = :id");
Try to make it work.
I think I am missing somewhere some annotation in order to avoid this kind of exception. I noticed in some examples they were using #IndexColumn but this annotation is deprecated.. Appreciate any directions for this.
I am using Spring-Security on top of a Spring-MVC application. I have my own implementation of UserDAO, userDetailsService. I am trying to authenticate by checking from database(ofcourse). I reach till the login page, everything seems to be working fine, but when I login, I get an error :
ERROR:
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - An internal error occurred while trying to authenticate the user.
org.springframework.security.authentication.InternalAuthenticationServiceException: Provided id of the wrong type for class com.WirTauschen.model.User. Expected: class java.lang.Integer, got class java.lang.String
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:110)
I do not know where am I retrieving or working with user's id. I am posting the code below.
LoginService :
#Service("userDetailsService")
public class LoginServiceImpl implements UserDetailsService{
#Autowired private UserDao userDao;
#Autowired private Assembler assembler;
#Override
#Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserDetails userDetails = null;
User user = userDao.findByName(username);
if(user == null) { throw new UsernameNotFoundException("Wrong username or password");} //Never specify which one was it exactly
return assembler.buildUserFromUserEntity(user);
}
}
Assembler
#Service("assembler")
public class Assembler {
#Transactional(readOnly = true)
User buildUserFromUserEntity(com.WirTauschen.model.User userEntity){
String username = userEntity.getUsername();
String password = userEntity.getPassword();
// int id = userEntity.getId();
boolean enabled = userEntity.isActive();
boolean accountNonExpired = userEntity.isAccountNonExpired();
boolean credentialsNonExpired = userEntity.isCredentialsNonExpired();
boolean accountNonLocked = userEntity.isAccountNonLocked();
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
User user1 = new User(username,password,enabled,accountNonExpired,credentialsNonExpired,accountNonLocked,authorities);
return user1;
}
}
User :
#Entity
#Table(name="registration")
public class User implements UserDetails{
private static final GrantedAuthority USER_AUTH = new SimpleGrantedAuthority("ROLE_USER");
#Id
#Column(name="id")
private String id=UUID.randomUUID().toString();
// #GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "my_entity_seq_gen")
//#SequenceGenerator(name ="my_entity_seq_gen", sequenceName = "MY_ENTITY_SEQ")
#OneToMany
private Set<ProductBasic> productBasic;
#Column(name = "email")
private String email;
#Column(name = "username")
private String Username;
#Column(name = "displayname")
private String DisplayName;
#Column(name = "password")
private String password;
#Column(name = "companyname")
private String CompanyName;
#Column(name = "firstname")
private String FirstName;
#Column(name = "middlename")
private String MiddleName;
private String role="ROLE_USER";
#Transient
private final String PERMISSION_PREFIX = "ROLE_USER";
#Transient
private List<GrantedAuthority> authorities;
public User() {
this.authorities = new ArrayList<GrantedAuthority>();
authorities.add(USER_AUTH);
}
public User(String Username, String password, String Role){
this.Username = Username;
this.password = password;
this.role = Role;
if((role == null) || role.isEmpty()){ role = "ROLE_USER";}
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
Update sequence code
#Id
#Column(name = "sortcanvasid")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sortcanvas_gen")
#SequenceGenerator(name = "sortcanvas_gen", sequenceName = "sortcanvas_seq")
private int sortCanvasId;
Seems that your User class not implementing UserDetails Morever it might not be having proper return type of the getID method