Hibernate + Spring exception: Unknown Entity - java

i am getting exception while the server starts. (Server is started using Intelij IDE).
i have no idea how to fix it. i am new to hibernate and spring. thanks in advance.
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationMgr' defined in URL [jar:file:/C:/Program%20Files%20(x86)/Apache%20Software%20Foundation/Tomcat%207.0/webapps/ROOT/WEB-INF/lib/dbservice-1.0-SNAPSHOT.jar!/ApplicationContext-Service.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'authenticationDao' threw exception; nested exception is org.springframework.orm.hibernate3.HibernateSystemException: Unknown entity: com.jsi.core.dbservice.model.Authentication; nested exception is org.hibernate.MappingException: Unknown entity: com.jsi.core.dbservice.model.Authentication
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1361)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4681)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5184)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5179)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
at java.lang.Thread.run(Thread.java:619)
Caused by: org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'authenticationDao' threw exception; nested exception is org.springframework.orm.hibernate3.HibernateSystemException: Unknown entity: com.jsi.core.dbservice.model.Authentication; nested exception is org.hibernate.MappingException: Unknown entity: com.jsi.core.dbservice.model.Authentication
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:102)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1358)
... 21 more
Authentication entity
/**
* Authentication Entity - Representation of the db table
*/
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
#Entity
#Table(name = "t_authentication")
public class Authentication extends LongBaseEntity implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "auth_id")
private Long mAuthId;
#Column(name = "authentication_id")
private Long mAuthenticationId;
#Column(name = "tcn")
private Long mTcn;
#Column(name = "audit_comment")
private String mAuditComment;
#Column(name = "last_timestamp")
private Date mLastTimeStamp;
#Column(name = "user_id")
private Long mUserId;
#Column(name = "authentication_date")
private Date mAuthenticationDate;
#Column(name = "hostname")
private String mHostname;
#Column(name = "ip_address")
private String mIpAddress;
#Column(name = "referrer_url")
private String mReferrerURL;
#Column(name = "session_id")
private String mSessionId;
public Long getAuthId() {
return mAuthId;
}
public void setAuthId(Long pAuthId) {
this.mAuthId = pAuthId;
mId = pAuthId;
}
public Long getAuthenticationId() {
return mAuthenticationId;
}
public void setAuthenticationId(Long pAuthenticationId) {
this.mAuthenticationId = pAuthenticationId;
}
public Long getTcn() {
return mTcn;
}
public void setTcn(Long pTcn) {
this.mTcn = pTcn;
}
public String getAuditComment() {
return mAuditComment;
}
public void setAuditComment(String pAuditComment) {
this.mAuditComment = pAuditComment;
}
public Date getLastTimeStamp() {
return mLastTimeStamp;
}
public void setLastTimeStamp(Date pLastTimeStamp) {
this.mLastTimeStamp = pLastTimeStamp;
}
public Long getUserId() {
return mUserId;
}
public void setUserId(Long pUserId) {
this.mUserId = pUserId;
}
public Date getAuthenticationDate() {
return mAuthenticationDate;
}
public void setAuthenticationDate(Date pAuthenticationDate) {
this.mAuthenticationDate = pAuthenticationDate;
}
public String getHostname() {
return mHostname;
}
public void setHostname(String pHostname) {
this.mHostname = pHostname;
}
public String getIpAddress() {
return mIpAddress;
}
public void setIpAddress(String pIpAddress) {
this.mIpAddress = pIpAddress;
}
public String getReferrerURL() {
return mReferrerURL;
}
public void setReferrerURL(String pReferrerURL) {
this.mReferrerURL = pReferrerURL;
}
public String getSessionId() {
return mSessionId;
}
public void setSessionId(String pSessionId) {
this.mSessionId = pSessionId;
}
public String toString() {
return "Payment{" +
"mId=" + getId() +
", mIpaddress=" + mIpAddress +
'}';
}
}
DAO class:
/**
* Implementation for AuthenticationMgr DAO layer.
*
*/
import com.jsi.core.dbservice.model.Authentication;
import com.jsi.core.dbservice.model.JSIException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import java.sql.SQLException;
import java.util.List;
public class AuthenticationDao extends HibernateDaoSupport implements IAuthenticationDao {
#Override
public List<Authentication> list() {
final String query = "Select a from Authentication a order by a.id desc";
return (List<Authentication>) getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
return session.createQuery(query).list();
}
});
}
#Override
public void save(Authentication authentication) throws JSIException {
getHibernateTemplate().save(authentication);
}
#Override
public Authentication load(Long id) {
return getHibernateTemplate().load(Authentication.class, id);
}
#Override
public void update(Authentication authentication) throws JSIException {
getHibernateTemplate().update(authentication);
}
#Override
public void delete(Long id) {
getHibernateTemplate().delete(load(id));
}
}

If you are happened to use HibernateUtil to manipulate the data, you need to add annotated class to your configuration.
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().addAnnotatedClass(Authentication.class)
.configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
http://docs.jboss.org/hibernate/stable/annotations/reference/en/html/ch01.html

thanks everyone for your reply. i managed to solve it. it was my mistake. i forgot to add the mapping tag in xml.
<hibernate-configuration>
<session-factory>
<mapping class="com.model.Authentication"/> // i missed this line. after i added it. it worked fine.
</session-factory>
</hibernate-configuration>
thanks again.

Related

Exception in thread "main" java.lang.Error: Unresolved compilation problems: Configuration cannot be resolved to a type

I'm getting this error message. I'm learning Hibernate, So don't know much about it
I'm new to Hibernate and don't know much about it. When I try to run the code written below I'm getting an error message.
***** This is my main class *****
package anubhav.DemoHibernate1;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class App
{
public static void main( String[] args )
{
Alien alien = new Alien();
alien.setAid(101);
alien.setAname("Anubhav");
alien.setColour("Green");
Configuration con = new Configuration().configure().addAnnotatedClass(Alien.class);
SessionFactory sf = con.buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
session.save(alien);
tx.commit();
}
}
***** This is the Alien class which I've created the object in my main class *****
package anubhav.DemoHibernate1;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Alien
{
#Id
private int aid;
private String aname;
private String colour;
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid = aid;
}
public String getAname() {
return aname;
}
public void setAname(String aname) {
this.aname = aname;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
}
Looks like local maven repo is not proper.
Delete .m2/repository/org/hibernate/*, then in eclipse: Maven/update Project. It will be re downloading the dependencies.
Also try cleaning the project in eclipse.

How to make unidirectional #oneToMany relationship for 2 tables using JPA and Hibernate

My project based on spring boot,Thymeleaf,mysql,html and Jquery.I tried to make a #oneToMany Relation with unidirectional in maintable,but it produces only error like
2017-10-23 16:17:49.908 ERROR 18724 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'entityManagerFactory' defined in class path
resource
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]:
Invocation of init method failed; nested exception is
org.hibernate.AnnotationException: **Unable to map collection
com.vfraternity.process.entity.EntPropertyMaster.blockListPropSub** at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1702)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1083)
~[spring-context-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:858)
~[spring-context-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
~[spring-context-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:122)
~[spring-boot-2.0.0.M4.jar:2.0.0.M4] at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750)
[spring-boot-2.0.0.M4.jar:2.0.0.M4] at
org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386)
[spring-boot-2.0.0.M4.jar:2.0.0.M4] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:327)
[spring-boot-2.0.0.M4.jar:2.0.0.M4] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1245)
[spring-boot-2.0.0.M4.jar:2.0.0.M4] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1233)
[spring-boot-2.0.0.M4.jar:2.0.0.M4] at
com.vfraternity.VfSpringBootMain.main(VfSpringBootMain.java:12)
[classes/:na] Caused by: org.hibernate.AnnotationException: Unable to
map collection
com.vfraternity.process.entity.EntPropertyMaster.blockListPropSub at
org.hibernate.cfg.annotations.CollectionBinder.bindCollectionSecondPass(CollectionBinder.java:1604)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.cfg.annotations.CollectionBinder.bindOneToManySecondPass(CollectionBinder.java:871)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:786)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:725)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:54)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1621)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1589)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:278)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:858)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:885)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57)
~[spring-orm-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:358)
~[spring-orm-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:384)
~[spring-orm-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:373)
~[spring-orm-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods AbstractAutowireCapableBeanFactory.java:1761)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1698)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] ... 16 common frames omitted
Caused by: org.hibernate.cfg.RecoverableException: Unable to find
column with logical name: propertysubpk in
org.hibernate.mapping.Table(property_master) and its related
supertables and secondary tables at
org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:831)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.cfg.BinderHelper.createSyntheticPropertyReference(BinderHelper.java:243)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.cfg.annotations.CollectionBinder.bindCollectionSecondPass(CollectionBinder.java:1594)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] ... 31 common frames
omitted Caused by: org.hibernate.MappingException: Unable to find
column with logical name: propertysubpk in
org.hibernate.mapping.Table(property_master) and its related
supertables and secondary tables at
org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:826)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] ... 33 common frames
omitted
I tried to achive unidirectional using
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="propertysubfkid", referencedColumnName="propertysubpk")
private List<EntPropertySub> blockListPropSub = newArrayList<EntPropertySub>();
But it produces only error...
Here is my complete codes..
**EntPropertyMaster**
package com.vfraternity.process.entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;
#Entity
#Table(name="Property_Master")
public class EntPropertyMaster implements Serializable{
/**
*
*/
private static final long serialVersionUID = 6162594257264775391L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="propertyid")
private int property_id;
#NotNull
private String property_name;
#NotNull
private String address1;
#NotNull
#Column(columnDefinition="varchar(15) default'None'")
private String address2;
#NotNull
private String city;
#NotNull
private String state;
#NotNull
private String country;
#NotNull
private int zipcode;
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="propertysubfkid", referencedColumnName="propertysubpk")
private List<EntPropertySub> blockListPropSub = new ArrayList<EntPropertySub>();
#Version
private int version;
private Boolean is_active;
private String created_by;
private Date created_ts;
private String modified_by;
private Date modified_ts;
private String approved_by;
private Date approved_ts;
public EntPropertyMaster() {
}
//Getter Setter
public int getProperty_id() {
return property_id;
}
public void setProperty_id(int property_id) {
this.property_id = property_id;
}
public String getProperty_name() {
return property_name;
}
public void setProperty_name(String property_name) {
this.property_name = property_name;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public Boolean getIs_active() {
return is_active;
}
public void setIs_active(Boolean is_active) {
this.is_active = is_active;
}
public String getCreated_by() {
return created_by;
}
public void setCreated_by(String created_by) {
this.created_by = created_by;
}
public Date getCreated_ts() {
return created_ts;
}
public void setCreated_ts(Date created_ts) {
this.created_ts = created_ts;
}
public String getModified_by() {
return modified_by;
}
public void setModified_by(String modified_by) {
this.modified_by = modified_by;
}
public Date getModified_ts() {
return modified_ts;
}
public void setModified_ts(Date modified_ts) {
this.modified_ts = modified_ts;
}
public String getApproved_by() {
return approved_by;
}
public void setApproved_by(String approved_by) {
this.approved_by = approved_by;
}
public Date getApproved_ts() {
return approved_ts;
}
public void setApproved_ts(Date approved_ts) {
this.approved_ts = approved_ts;
}
public int getZipcode() {
return zipcode;
}
public void setZipcode(int zipcode) {
this.zipcode = zipcode;
}
public List<EntPropertySub> getBlockListPropSub() {
return blockListPropSub;
}
public void setBlockListPropSub(List<EntPropertySub> blockListPropSub) {
this.blockListPropSub = blockListPropSub;
}
}
/////////////////////////////////////////////////////////////
EntPropertySub
package com.vfraternity.process.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;
#Entity
#Table(name="propertysub")
public class EntPropertySub implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 810618405796553525L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="propertysubpk")
private int propertySub_pk;
#NotNull
private String blockname;
#NotNull
private int floors;
#NotNull
private String flatstart;
private String flatend;
#Version
private int version;
private Boolean is_active;
private String created_by;
private Date created_ts;
private String modified_by;
private Date modified_ts;
private String approved_by;
private Date approved_ts;
public EntPropertySub() {
}
//Getter Setter
public int getPropertySub_pk() {
return propertySub_pk;
}
public void setPropertySub_pk(int propertySub_pk) {
this.propertySub_pk = propertySub_pk;
}
public String getBlockname() {
return blockname;
}
public void setBlockname(String blockname) {
this.blockname = blockname;
}
public int getFloors() {
return floors;
}
public void setFloors(int floors) {
this.floors = floors;
}
public String getFlatstart() {
return flatstart;
}
public void setFlatstart(String flatstart) {
this.flatstart = flatstart;
}
public String getFlatend() {
return flatend;
}
public void setFlatend(String flatend) {
this.flatend = flatend;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public Boolean getIs_active() {
return is_active;
}
public void setIs_active(Boolean is_active) {
this.is_active = is_active;
}
public String getCreated_by() {
return created_by;
}
public void setCreated_by(String created_by) {
this.created_by = created_by;
}
public Date getCreated_ts() {
return created_ts;
}
public void setCreated_ts(Date created_ts) {
this.created_ts = created_ts;
}
public String getModified_by() {
return modified_by;
}
public void setModified_by(String modified_by) {
this.modified_by = modified_by;
}
public Date getModified_ts() {
return modified_ts;
}
public void setModified_ts(Date modified_ts) {
this.modified_ts = modified_ts;
}
public String getApproved_by() {
return approved_by;
}
public void setApproved_by(String approved_by) {
this.approved_by = approved_by;
}
public Date getApproved_ts() {
return approved_ts;
}
public void setApproved_ts(Date approved_ts) {
this.approved_ts = approved_ts;
}
}
Please help me to solve this..Thanks in advance
The cause of the error is:
Unable to find column with logical name: propertysubpk in org.hibernate.mapping.Table(property_master)
The reason is that you have the referencedColumnName attribute wrong. It is supposed to be:
JPA 2.1 11.1.25: The name of the column referenced
by this foreign key column. When
used with entity relationship mappings
other than the cases described below, the
referenced column is in the table of the target
entity. When used with a unidirectional
OneToMany foreign key mapping, the referenced
column is in the table of the
source entity. When used inside a Join-
Table annotation, the referenced key column
is in the entity table of the owning
entity, or inverse entity if the join is part of
the inverse join definition. When used in a
collection table mapping, the referenced
column is in the table of the entity containing
the collection.
To explain: a #JoinColumn creates a column in the many side of the relation (the EntPropertySub here) with the given name that references the PK of the parent entity, unless referencedColumnName is specified. In the latter case the FK in the "many" table references the column given in referencedColumnName. In your case you want to reference the PK of EntPropertyMaster, so referencedColumnName is redundant. Simply use:
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="propertysubfkid")
private List<EntPropertySub> blockListPropSub = newArrayList<EntPropertySub>();
Try this: make sure how the foreign key in the table EntPopertySub called
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="propertyid")
private List<EntPropertySub> blockListPropSub = new ArrayList<EntPropertySub>();
It's not possible to create a physical column on the master table because you have a OneToMany relation. OneToMany means that Master has many Sub Table references.
Let's explain the Problem:
If you would have a column in the master table you need to would add a list of references in one cell.
For Example
------------------
| sub-fk |
|1, 2, 3, 4| <-- and this is against the database normalization
But this is not necessary:
Hibernate will automatically select all the referenced sub-columns for you (intern hibernate joins to the columns)
If you use the entitymanager to select the master data, the sub-data is included in the List blockListPropSub attribute
When you use the #JoinColumn on a #OneToMany relationship, the name attribute will point to the relating tables column, that is EntPropertySub entity and the referencedColumnName should be pointing to the column of the entity in which the #OneToMany annotation is present, that is EntPropertyMaster.
So basically you have it other way round and it should be in my opinion:
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="propertysubpk", referencedColumnName="propertysubfkid")
private List<EntPropertySub> blockListPropSub = newArrayList<EntPropertySub>();
The error clearly shows mapping missing in your schema relation.
You need to map EntPropertyMaster in EntPropertySub.
#OneToMany(cascade=CascadeType.ALL, mappedBy="entPropertyMaster")
private List<EntPropertySub> blockListPropSub = newArrayList<EntPropertySub>();
Provide EntPropertyMaster mapping in relation entity too.i.e.
#ManyToOne
#JoinColumn(name="entPropertyMasterId",referencedColumnName="id")
private EntPropertyMaster entPropertyMaster;
Relationships in JPA are always unidirectional, unless you associate
the parent with the child in both directions. Cascading REMOVE
operations from the parent to the child will require a relation from
the parent to the child (not just the opposite).
Finnaly i got a answer..
i made a changes in master entity "EntPropertyMaster"
"#OneToMany(cascade=CascadeType.ALL)"
"#JoinColumn(name="propertyidfk")"
private List<EntPropertySub> blockListPropSub = new ArrayList<EntPropertySub>();
It will create column in child table,but i wrote this code in parent Entity...
Please Note we need to give unique name for column creation,Then only it creates a column in child table.... not a primarykey column name
of child /parent table..

Spring boot, does not create beans #Controller, #Service

This is my project directory structure.
All controller and other classes and directories, which are beans, are under the "WebPortalApplication" class, and as Spring Boot doc states, we do not explicitly specify the package to scan for beans, whenever those packages locate unther the "main" class directory, right?
So when I run the "WebPortalApplication" file, it builds, but with such exceptions.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userRestController': Unsatisfied dependency expressed through field 'userService';
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'roleRepository';
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'roleRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException:
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.epam.webPortal.model.Role
#RestController
public class UserRestController {
#Autowired
UserService userService;
private static final Logger LOGGER = LoggerFactory.getLogger(UserRestController.class);
//-------------------Retrieve All Users--------------------------------------------------------
#RequestMapping(value = "/user/", method = RequestMethod.GET)
public String listAllUsers() {
String userAsJson = "";
List<User> users = userService.findAllUsers();
try {
userAsJson = JsonConvertor.toJson(users);
} catch (Exception ex) {
LOGGER.error("Something went wrong during converting json format");
}
LOGGER.info("displaying all users in json format");
return userAsJson;
}
package com.epam.webPortal.service.user;
import com.epam.webPortal.model.User;
import com.epam.webPortal.repository.role.RoleRepository;
import com.epam.webPortal.repository.user.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional
import java.util.Date;
import java.util.HashSet;
import java.util.List;
#Service("userService")
#Transactional
public class UserServiceImpl implements UserService {
private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
#Autowired
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
#Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
#Override
public void saveUser(User user) {
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
user.setRoles(new HashSet<>(roleRepository.findAll()));
user.setDateRegistered(new Date());
userRepository.save(user);
LOGGER.info("user with username {} successfully saved", user.getUsername());
}
#Override
public User findByUsername(String username) {
return userRepository.findByUsername(username);
}
#Override
public List<User> findAllUsers() {
return userRepository.findAllUsers();
}
#Override
public User findById(Long Id) {
return userRepository.findById(Id);
}
#Override
public void updateUser(User user) {
final User entity = userRepository.findById(user.getId());
if (entity != null) {
entity.setFirstName(user.getFirstName());
entity.setLastName(user.getLastName());
entity.setEmail(user.getEmail());
entity.setSkypeID(user.getSkypeID());
entity.setDateRegistered(new Date());
entity.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
userRepository.save(entity);
LOGGER.info("user with id {} successfully updated", user.getId());
}
}
#Override
public void deleteUserById(Long id) {
userRepository.deleteById(id);
LOGGER.info("user with id {} successfully deleted", id);
}
}
package com.epam.webPortal.model;
import javax.persistence.*;
import java.util.Set;
#Entity
#Table(name = "role")
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
#ManyToMany(mappedBy = "roles", fetch = FetchType.EAGER)
private Set<User> users;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
}
It looks like you're using JPA.
All JPA entities must be annotated with #Entity.
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.epam.webPortal.model.Role
means, Role class is missing #Entity annotation.
Have you enabled your repos?
#SpringBootApplication
#EnableJpaRepositories
public class WebPortalApplication {
public static void main(String[] args) {
SpringApplication.run(WebPortalApplication.class, args);
}
}
I expect below definition on your RoleRepository; sharing this file will help to further analyze on what is missing.
public interface RoleRepository implements CrudRepository<Role, Long> {
...
}

Spring: detached entity passed to persist

It is a short time that I'm studying Spring,I'm a student
I have problems with dependency injection. In this project I have this error code in the method acquista.Why? Acquista in english is translated in "buy".If my Carrello (cart) is composed by more than one Articolo(Article) , in ArticoliOrdine(ArticlesOrder) I have only the first of them.Why?How can I solve it?
Error code:
Grave: Servlet.service() for servlet [applicationContext] in context with path [/SpringStore] threw exception [Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: bean.Ordine] with root cause
org.hibernate.PersistentObjectException: detached entity passed to persist: bean.Ordine
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:139)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:289)
at com.sun.proxy.$Proxy37.persist(Unknown Source)
at daoJPA.CarrelloDAOImpl.acquista(CarrelloDAOImpl.java:130)
CarrelloDAOImpl.java
#Transactional
public class CarrelloDAOImpl implements CarrelloDAO {
#PersistenceContext
private EntityManager em;
#Autowired
Carrello carrello;
#Autowired
private ArticoliOrdine articoliOrdine;
#Autowired
private Ordine ordine;
public void acquista(Cliente c){
ordine.setIdCliente(c);
ordine.setData(new Date(System.currentTimeMillis()));
ordine.setStato("In lavorazione");
em.persist(ordine);
Set<String> lista_articoli=carrello.getMappa_Articoli().keySet();
synchronized(lista_articoli){
Iterator<String> it=lista_articoli.iterator();
while(it.hasNext()){
String codice=it.next();
System.out.println("codice: "+codice);
Query q=em.createQuery("SELECT a FROM Articolo a WHERE a.codice =:codice");
q.setParameter("codice", codice);
Articolo a =(Articolo)q.getSingleResult();
ArticoliOrdinePK pk=articoliOrdine.getArticoliordinePK();
pk.setIdArticolo(a.getId());
pk.setIdOrdine(ordine.getId());
articoliOrdine.setArticolo(a);
articoliOrdine.setQuantita(carrello.getMappa_Articoli().get(codice));
em.persist(articoliOrdine);
//aggiorno la quantita' dell'articolo
Articolo articolo_update=em.find(Articolo.class,a.getId());
articolo_update.setQuantita(articolo_update.getQuantita()- articoliOrdine.getQuantita());
}//while
}//syncronized
}//acquista
}//CarrelloDAOImpl
Ordine.java
#Table(name="ordine")
#Entity
public class Ordine implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Integer id;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="data")
private Date data;
#Column(name="stato")
private String stato;
#ManyToOne(optional=false)
#JoinColumn(name="idCliente",referencedColumnName="id")
private Cliente idCliente;
#OneToMany(mappedBy="ordine",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
Collection<ArticoliOrdine> articoliordineCollection;
public Ordine() {
}
public Ordine(Integer id) {
this.id = id;
}
public Ordine(Integer id, Date data, String stato) {
this.id = id;
this.data = data;
this.stato = stato;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public String getStato() {
return stato;
}
public void setStato(String stato) {
this.stato = stato;
}
public Cliente getIdCliente() {
return idCliente;
}
public void setIdCliente(Cliente idCliente) {
this.idCliente = idCliente;
}
public Collection<ArticoliOrdine> getArticoliordineCollection() {
return articoliordineCollection;
}
public void setArticoliordineCollection(
Collection<ArticoliOrdine> articoliordineCollection) {
this.articoliordineCollection = articoliordineCollection;
}
#Override
public boolean equals(Object o){
if(! (o instanceof Ordine) )
return false;
Ordine ordine=(Ordine)o;
return ordine.id==this.id;
}//equals
public String toString(){
return id+" cliente:"+idCliente.getId();
}//toString
}//Ordine
CarrelloController.java
#Controller
public class CarrelloController {
#Autowired
CarrelloDAO carrelloDAO;
#Autowired
Carrello carrello;
...
#RequestMapping(value="/acquista",method=RequestMethod.POST)
public String acquista(HttpServletRequest request,ModelMap model){
HttpSession session=request.getSession();
Cliente cliente=(Cliente)session.getAttribute("cliente");
carrelloDAO.acquista(cliente);
carrello.svuotaCarrello();
model.addAttribute("num_articoli",carrello.contaArticoliCarrello());
model.addAttribute("totale_carrello",carrello.getTotale());
return "redirect:/";
}//checkOut
}//CarrelloController
ApplicationContext.xml
<bean class="daoJPA.ClienteDAOImpl" id="clienteDAO"/>
<bean class="daoJPA.ArticoloDAOImpl" id="articoloDAO"/>
<bean class="bean.Carrello" id="carrello" scope="session">
<aop:scoped-proxy/>
</bean>
<bean class="daoJPA.CarrelloDAOImpl" id="carrelloDAO"/>
<bean class="bean.ArticoliOrdine" id="articoliOrdine" scope="prototype">
<property name="articoliordinePK">
<bean class="bean.ArticoliOrdinePK" id="articoliOrdinePK" scope="prototype"/>
</property>
</bean>
<bean class="bean.Ordine" id="ordine" scope="prototype"/>
You are not approaching this the right way. Your entities shouldn't be treated as Spring Beans.
#Autowired
private ArticoliOrdine articoliOrdine;
...
em.persist(articoliOrdine);
For long conversations you should either use:
Extended persistence context
detached objects saved in your Http Session
And detached entities shouldn't be passed to persist. You should merge them instead.
Persist is only meant for moving an entity state from TRANSIENT to PERSISTED. For DETACHED -> PERSISTED transitions you should always use EntityManager#merge() or Hibernate specific saveOrUpdate.

the value of the field moduleService is not Used

package com.maroclance.university.service;
import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ModuleServiceTest {
public class ModuleServiceTest {
private static ClassPathXmlApplicationContext context;
private static ModuleService moduleService;
#BeforeClass
public static void setUpBeforeClass() throws Exception {
context = new ClassPathXmlApplicationContext("application-context.xml");
moduleService=(ModuleService) context.getBean("moduleService");
}
#AfterClass
public static void tearDownAfterClass() throws Exception {
context.close();
}
#Test
public void test() {
fail("Not yet implemented");
}
}
i have the warning that moduleService is not used
when i execute my code i have this error
rg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [application-context.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class: com.maroclance.model.Matiere.profMats[com.maroclance.model.ProfMat]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1401)
.
.
.
.
aused by: org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class: com.maroclance.model.Matiere.profMats[com.maroclance.model.ProfMat]
at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1068)
I'm really blocked
One of the classes ProfMat or Module has not mapped with Hibernate. The mapping should be defined via configuration. If you are using annotation configuration then put a #Table annotation on the associated classes and make sure that classes are scanned for annotations.
package com.maroclance.university.model;
// Generated 19 sept. 2014 13:34:26 by Hibernate Tools 3.4.0.CR1
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* Matiere generated by hbm2java
*/
#SuppressWarnings("serial")
#Entity
#Table(name = "matiere", catalog = "gestionmatiere")
public class Matiere implements java.io.Serializable {
private int id;
private String nomMatiere;
private int coefficient;
private Set<ProfMat> profMats = new HashSet<ProfMat>(0);
private Set<Module> modules = new HashSet<Module>(0);
public Matiere() {
}
public Matiere(int id, String nomMatiere, int coefficient) {
this.id = id;
this.nomMatiere = nomMatiere;
this.coefficient = coefficient;
}
public Matiere(int id, String nomMatiere, int coefficient,
Set<ProfMat> profMats, Set<Module> modules) {
this.id = id;
this.nomMatiere = nomMatiere;
this.coefficient = coefficient;
this.profMats = profMats;
this.modules = modules;
}
#Id
#Column(name = "id", unique = true, nullable = false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "nom_matiere", nullable = false, length = 20)
public String getNomMatiere() {
return this.nomMatiere;
}
public void setNomMatiere(String nomMatiere) {
this.nomMatiere = nomMatiere;
}
#Column(name = "coefficient", nullable = false)
public int getCoefficient() {
return this.coefficient;
}
public void setCoefficient(int coefficient) {
this.coefficient = coefficient;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "matiere")
public Set<ProfMat> getProfMats() {
return this.profMats;
}
public void setProfMats(Set<ProfMat> profMats) {
this.profMats = profMats;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "matiere")
public Set<Module> getModules() {
return this.modules;
}
public void setModules(Set<Module> modules) {
this.modules = modules;
}
}

Categories

Resources