Unknown column error using hibernate OneToMany mapping - java

I m new to hibernate and having error Unknown column in OneToMany mapping. I m trying to implement the one to many relationships using hibernate but having an error.
Here is my Code:
Department Class:
#Entity
#Table(name="department")
public class Department {
#Id
#Column(name="dept_id")
private int id;
#Column(name="dept_name")
private String name;
#OneToMany(mappedBy="department", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
private Collection<Employee> employees = new ArrayList<Employee>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Collection<Employee> getEmployees() {
return employees;
}
public void setEmployees(Collection<Employee> employees) {
this.employees = employees;
}
}
Employee Class:
#Entity
#Table(name = "employee")
public class Employee {
#Column(name="emp_id")
#Id
private int id;
#Column(name="emp_name")
private String name;
#ManyToOne
private Department department;
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Employee Dao Class:
public class EmployeeDao {
public void addEmployee(Employee emp, int id){
Department department = new Department();
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
department = (Department) session.get(Department.class, id);
emp.setDepartment(department);
department.getEmployees().add(emp);
session.save(emp);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
}
Here is my Database :
CREATE TABLE `department` (
`dept_id` int(11) NOT NULL,
`dept_name` varchar(255) DEFAULT NULL
)
CREATE TABLE `employee` (
`emp_id` int(11) NOT NULL,
`emp_name` varchar(255) DEFAULT NULL,
`dept_id` int(11) DEFAULT NULL
)
Stack Trace :
WARNING: #{employee.addEmployee}: org.hibernate.exception.SQLGrammarException: could not load an entity: [com.hibCollection.bean.Department#0]
javax.faces.FacesException: #{employee.addEmployee}: org.hibernate.exception.SQLGrammarException: could not load an entity: [com.hibCollection.bean.Department#0]
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:722)
Caused by: javax.faces.el.EvaluationException: org.hibernate.exception.SQLGrammarException: could not load an entity: [com.hibCollection.bean.Department#0]
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 27 more
Caused by: org.hibernate.exception.SQLGrammarException: could not load an entity: [com.hibCollection.bean.Department#0]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.loader.Loader.loadEntity(Loader.java:2041)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:86)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:76)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3293)
at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:496)
at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:477)
at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:227)
at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:285)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:152)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:1090)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:1005)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:998)
at com.hibCollection.dao.EmployeeDao.addEmployee(EmployeeDao.java:21)
at com.hibCollection.mangedBean.EmployeeManageBean.addEmployee(EmployeeManageBean.java:29)
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:601)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 28 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'employees1_.department_dept_id' in 'field list'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1031)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3376)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3308)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1837)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1961)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2543)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1737)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1888)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1953)
at org.hibernate.loader.Loader.doQuery(Loader.java:802)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
at org.hibernate.loader.Loader.loadEntity(Loader.java:2037)
... 49 more
Can you please tell me what I'm doing wrong here? :)

Try make so
#ManyToOne
#JoinColumn(name = "dept_id")
private Department department;

The default column name for mapping is of type,
table_name + '_' + target_table_primary_key. This is why it is looking for department_dept_id
You can specify mapping column using annotations. #JoinColumn(name="dept_id").

Property-based access is the right way for using #OneToMany and #ManyToOne annotation
Use #OneToMany like below:
private Collection<Employee> employees;
#OneToMany(mappedBy="department", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
public Collection<Employee> getEmployees() {
return employees;
}
public void setEmployees(Collection<Employee> employees) {
this.employees = employees;
}
And use #ManyToOne like below:
private Department department;
#ManyToOne
#JoinColumn(name = "dept_id")
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
Also you need to use an empty constructor in your model classes, as hibernate wants it.
If you use #OnetoMany and #ManyToOne with File-based access then you will get the following error
Initial SessionFactory creation failed.org.hibernate.MappingException: Could not determine type for: java.util.List, for columns: [org.hibernate.mapping.Column(relatedResources)]

Related

Springboot mvc java application cannot run when it's set to UPDATE

My web application was working until I decided to put in comments. I messed it up a lot so I changed spring.jpa.hibernate.ddl-auto from upate to create-drop
But now, when I spring.jpa.hibernate.ddl-auto = create-drop the application starts and when I change it to spring.jpa.hibernate.ddl-auto = update I get this error:
2017-11-27 15:27:02.481 ERROR 3552 --- [ restartedMain] 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 javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1078) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
at blog.BlogApplication.main(BlogApplication.java:14) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_111]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_111]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_111]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_111]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.8.RELEASE.jar:1.5.8.RELEASE]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
... 21 common frames omitted
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Unable to execute schema management to JDBC target [alter table comments add constraint FK99rehd3fcds7jsy5dpa39fitm foreign key (comments) references users (id)]
at org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:59) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlString(SchemaMigratorImpl.java:431) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlStrings(SchemaMigratorImpl.java:420) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applyForeignKeys(SchemaMigratorImpl.java:386) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigrationToTargets(SchemaMigratorImpl.java:214) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:60) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:134) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:101) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:472) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
... 27 common frames omitted
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: BLOB/TEXT column 'comments' used in key specification without a key length
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_111]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_111]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_111]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_111]
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.Util.getInstance(Util.java:408) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2483) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1552) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2607) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1480) ~[mysql-connector-java-5.1.44.jar:5.1.44]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_111]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_111]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_111]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_111]
at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114) ~[tomcat-jdbc-8.5.23.jar:na]
at com.sun.proxy.$Proxy88.executeUpdate(Unknown Source) ~[na:na]
at org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:56) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
... 37 common frames omitted
Probably some of my relations are messed up, but I have an ArticleBindingModel
public class ArticleBindingModel
{
private String comments;
#NotNull
private String title;
#NotNull
private String content;
//--------------------------GETTERS/SETTERS---------------------------
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public String getContent()
{
return content;
}
public void setContent(String content)
{
this.content = content;
}
public String getComments()
{
return comments;
}
public void setComments(String comments)
{
this.comments = comments;
}
}
Article Entity
#Entity
#Table(name = "articles")
public class Article
{
private Integer id;
private String title;
private String content;
private User author;
private User commenter;
private Set<Comment> comments;
//-----------------------------CONSTRUCTORS--------------------------
public Article(String title, String content, User author)
{
this.title = title;
this.content = content;
this.author = author;
this.comments = new HashSet<>();
}
public Article(){}
//-------------------------GETTERS/SETTERS----------------------------
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
#Column(nullable = false)
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
#Column(columnDefinition = "text", nullable = false)
public String getContent()
{
return content;
}
public void setContent(String content)
{
this.content = content;
}
#ManyToOne()
#JoinColumn(nullable = false, name = "authorId")
public User getAuthor()
{
return author;
}
public void setAuthor(User author)
{
this.author = author;
}
#OneToMany(mappedBy = "article")
public Set<Comment> getComments()
{
return comments;
}
public void setComments(Set<Comment> comments)
{
this.comments = comments;
}
}
Comment Entity
#Entity
#Table(name = "comments")
public class Comment
{
private Integer id;
private User commenter;
private String comments;
private Article article;
//-----------------------------CONSTRUCTORS----------------------
public Comment(User commenter, String comments, Article article)
{
this.commenter = commenter;
this.comments = comments;
this.article = article;
}
public Comment(){}
//----------------------METHODS-----------------------------------
//--------------------GETTERS/SETTERS-----------------------------
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
#Column(nullable = false, columnDefinition = "LONGBLOB")
public String getComments()
{
return comments;
}
public void setComments(String comments)
{
this.comments = comments;
}
#ManyToOne()
#JoinColumn(nullable = false, name = "commenterId")
public User getCommenter()
{
return commenter;
}
public void setCommenter(User commenter)
{
this.commenter = commenter;
}
#ManyToOne()
#JoinColumn(nullable = false, name = "articleId")
public Article getArticle()
{
return article;
}
public void setArticle(Article article)
{
this.article = article;
}
}
User Entity
#Entity
#Table(name = "users")
public class User
{
private Integer id;
private String username;
private Set<Article> articles;
private Set<Comment> comments;
//-----------------------------------CONSTRUCTORS-----------------------------------
public User (String username)
{
this.username = username;
this.articles = new HashSet<>();
this.comments = new HashSet<>();
}
public User() {
}
//------------------------------------METHODS------------------------------------------
//----------------------------------GETTERS/SETTERS--------------------------------------
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
#Column(name = "username", length = 80, nullable = false, unique = true)
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
#OneToMany(mappedBy = "author")
public Set<Article> getArticles()
{
return articles;
}
public void setArticles(Set<Article> articles)
{
this.articles = articles;
}
#OneToMany(mappedBy = "comments")
public Set<Comment> getComments()
{
return comments;
}
public void setComments(Set<Comment> comments)
{
this.comments = comments;
}
}
And then I have a repository for the appropriate Entities. I have heavily edited the code so I won't be a "heresallmycode" guy. But, I'm pretty sure that my annotation relations are the problem. I wanted there to be comments that have a MANY TO ONE relationship with an article, a user that would appear above the comments when they are posted and a reverse ONE TO MANY relationship of the article with the comments. When the tables are created using the create paramater, my articles table was not emptied(I had it on update before), I had to manually drop it. Now, when the table is created it's empty. I thought that was worth mentioning. I can post the create logs If that would be neccessary.
EDIT
I forgot my ArticleController
#Controller
public class ArticleController
{
#Autowired
private ArticleRepository articleRepository;
#Autowired
private UserRepository userRepository;
#Autowired
private CommentRepository commentRepository;
//---------------------------------METHODS-----------------------
//ARTICLE DETAILS--------------------------------------------------
#GetMapping("/article/{id}")
public String details(Model model, #PathVariable Integer id)
{
if (!this.articleRepository.exists(id))
{
return "redirect:/";
}
UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();//This was inside the IF
if (!(SecurityContextHolder.getContext().getAuthentication() instanceof AnonymousAuthenticationToken))
{
User entityUser = this.userRepository.findByEmail(principal.getUsername());
model.addAttribute("user", entityUser);
}
//Getting the article
Article article = this.articleRepository.findOne(id);
//Comments
Set<Comment> comments = this.commentRepository.findCommentsByArticleId(id);//findAllByArticlesId
//Set<User> commenters = this.userRepository.findAllByComments(comments);
//Models
model.addAttribute("article", article);
//model.addAttribute("commenters", commenters);
model.addAttribute("comments", comments);
model.addAttribute("view", "article/details");
return "base-layout";
}
#PostMapping("/article/{id}")
#PreAuthorize("isAuthenticated()")
public String detailsProcess(#PathVariable Integer id, ArticleBindingModel articleBindingModel)
{
if (!this.articleRepository.exists(id))
{
return "redirect:/";
}
//Getting the article
Article article = this.articleRepository.findOne(id);
//Getting the commenter
UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
User commenter = this.userRepository.findByEmail(principal.getUsername());
//Setting the values for the comment section
return "redirect:/article/{id}";
}
}
You have defined the relation to User in Comment as:
#ManyToOne()
#JoinColumn(nullable = false, name = "commenterId")
public User getCommenter()
{
return commenter;
}
but you are referring to comments string column on the Comment side of the relationship. You should change the mappedBy to:
#OneToMany(mappedBy = "commenter")
public Set<Comment> getComments()
{
return comments;
}

Spring JPA, #JointTable annotation not working

What is wrong: I'm trying to implement login using Spring Security. I'm using Spring Security's default endpoint login. I keep receiving 500s and I believe it's due to incorrect joint because when I'm printing
public Set<Role> getRoles() {
System.out.println("roles");
System.out.println(roles);
return roles;
}
roles is null. 'll show my stack trace at the end of the question.
What I want to have: correct working join.
My code
Join:
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(
name = "userrole",
joinColumns = #JoinColumn(name = "iduser"),
inverseJoinColumns = #JoinColumn(name = "roleid"))
private Set<Role> roles;
Whole Users model:
#Entity
#Table(name = "user_1")
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "iduser")
private Integer id;
#Column(name="id_points")
private Integer idPoints;
#Column(name="username")
private String userName;
#Column(name="isblocked")
private Boolean isBlocked;
#Column(name="email")
private String email;
#Column(name="lastname")
private String lastName;
#Column(name="firstname")
private String firstName;
#Column(name="password")
private String password;
#Column(name="token")
private String token;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(
name = "userrole",
joinColumns = #JoinColumn(name = "iduser"),
inverseJoinColumns = #JoinColumn(name = "roleid"))
private Set<Role> roles;
public Users() {
}
public Users(Users users) {
this.id = users.getId();
this.idPoints = users.getIdPoints();
this.userName = users.getUserName();
this.isBlocked = users.getBlocked();
this.email = users.getEmail();
this.lastName = users.getLastName();
this.firstName = users.getFirstName();
this.password = users.getPassword();
this.token = users.getToken();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getIdPoints() {
return idPoints;
}
public void setIdPoints(Integer idPoints) {
this.idPoints = idPoints;
}
public String getUserName() {
System.out.println(userName);
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Boolean getBlocked() {
return isBlocked;
}
public void setBlocked(Boolean blocked) {
isBlocked = blocked;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public Set<Role> getRoles() {
System.out.println("roles");
System.out.println(roles);
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
CustomUsersDetails:
package com.shareabook.model;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.stream.Collectors;
public class CustomUserDetails extends Users implements UserDetails {
public CustomUserDetails(final Users users) {
super(users);
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles()
.stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role.getRole()))
.collect(Collectors.toList());
}
#Override
public String getPassword() {
return super.getPassword();
}
#Override
public String getUsername() {
return super.getUserName();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
Role model
#Entity
#Table(name = "role")
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "roleid")
private Integer role_id;
#Column(name = "role")
private String role;
public Role() {
}
public Integer getRole_id() {
return role_id;
}
public void setRole_id(Integer role_id) {
this.role_id = role_id;
}
public String getRole() {
System.out.println("role");
System.out.println(role);
return role;
}
public void setRole(String role) {
this.role = role;
}
}
How I create database:
CREATE TABLE Role (
roleId INTEGER NOT NULL,
role VARCHAR NOT NULL,
CONSTRAINT pkrole PRIMARY KEY (roleId)
);
CREATE SEQUENCE user_1_iduser_seq;
CREATE TABLE User_1 (
idUser INTEGER NOT NULL DEFAULT nextval('user_1_iduser_seq'),
id_points INTEGER NOT NULL,
userName VARCHAR NOT NULL,
isBlocked BOOLEAN DEFAULT False NOT NULL,
email VARCHAR NOT NULL,
lastName VARCHAR NOT NULL,
firstName VARCHAR NOT NULL,
password VARCHAR NOT NULL,
token VARCHAR,
CONSTRAINT pkuser PRIMARY KEY (idUser)
);
ALTER SEQUENCE user_1_iduser_seq OWNED BY User_1.idUser;
CREATE TABLE userRole (
idUser INTEGER NOT NULL,
roleId INTEGER NOT NULL
);
ALTER TABLE userRole ADD CONSTRAINT role_userrole_fk
FOREIGN KEY (roleId)
REFERENCES Role (roleId)
ON DELETE NO ACTION
ON UPDATE NO ACTION
NOT DEFERRABLE;
ALTER TABLE User_1 ADD CONSTRAINT points_us_fk
FOREIGN KEY (id_points)
REFERENCES Points (idPoints)
ON DELETE CASCADE
ON UPDATE CASCADE
NOT DEFERRABLE;
ALTER TABLE userRole ADD CONSTRAINT user_1_userrole_fk
FOREIGN KEY (idUser)
REFERENCES User_1 (idUser)
ON DELETE NO ACTION
ON UPDATE NO ACTION
NOT DEFERRABLE;
How I populate databse with data:
INSERT INTO Role VALUES(1, 'ADMIN');
INSERT INTO Role VALUES(2, 'USER');
INSERT INTO Publisher VALUES(1, 'Zielona Sowa');
INSERT INTO Category VALUES(1,'kryminal');
INSERT INTO Points VALUES(1,20);
INSERT INTO Author VALUES(1, 'Tolkien', 'John Ronald Reuel');
INSERT INTO User_1 VALUES(1,1,'oliwka',false,'oliwka#wp.pl','m','o','jakies');
INSERT INTO userRole VALUES(1,1);
INSERT INTO Book VALUES(1,1,1,'Hobbit',null,3,false,1937);
INSERT INTO BooksByAuthors VALUES(1,1,1);
INSERT INTO BooksByCategory VALUES(1,1,1);
Stack trace:
Hibernate: select users0_.iduser as iduser1_1_, users0_.email as email2_1_, users0_.firstname as firstnam3_1_, users0_.id_points as id_point4_1_, users0_.isblocked as isblocke5_1_, users0_.lastname as lastname6_1_, users0_.password as password7_1_, users0_.token as token8_1_, users0_.username as username9_1_ from user_1 users0_ where users0_.username=?
Hibernate: select roles0_.iduser as iduser1_2_0_, roles0_.roleid as roleid2_2_0_, role1_.roleid as roleid1_0_1_, role1_.role as role2_0_1_ from userrole roles0_ inner join role role1_ on roles0_.roleid=role1_.roleid where roles0_.iduser=?
oliwka
roles
null
2017-10-29 15:04:50.241 ERROR 11896 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
java.lang.NullPointerException: null
at com.shareabook.model.CustomUserDetails.getAuthorities(CustomUserDetails.java:18) ~[classes/:na]
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.createSuccessAuthentication(AbstractUserDetailsAuthenticationProvider.java:225) ~[spring-security-core-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:197) ~[spring-security-core-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174) ~[spring-security-core-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:199) ~[spring-security-core-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) ~[spring-security-web-4.2.2.RELEASE.jar:4.2.2.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.14.jar:8.5.14]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_77]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_77]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.14.jar:8.5.14]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_77]
The association between User and Role is Many-to-Many and not One-to-many.
Change your mappings like so in the User entity
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(
joinColumns = #JoinColumn(name = "iduser"),
inverseJoinColumns = #JoinColumn(name = "roleid")
)
private Set<Role> roles;

Hibernate Criteria unable to retrieve collection of a nested object

I have got a TeamPlayer object with a Player object as on of its attribute. The Player object has One-to-Many relation with PlayerSuspension.
When I try to retrieve all TeamPlayers and fetch all player's suspensions along with. It throws following error. Could you help me out where's the issue?
org.hibernate.QueryException: could not resolve property: ps of: we.data.weref.model.TeamPlayer
at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:62)
at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:56)
at org.hibernate.persister.entity.AbstractEntityPersister.getSubclassPropertyTableNumber(AbstractEntityPersister.java:1770)
at org.hibernate.persister.entity.BasicEntityPropertyMapping.toColumns(BasicEntityPropertyMapping.java:46)
at org.hibernate.persister.entity.AbstractEntityPersister.toColumns(AbstractEntityPersister.java:1745)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getColumns(CriteriaQueryTranslator.java:510)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.findColumns(CriteriaQueryTranslator.java:525)
at org.hibernate.criterion.NullExpression.toSqlString(NullExpression.java:36)
at org.hibernate.criterion.LogicalExpression.toSqlString(LogicalExpression.java:42)
at org.hibernate.criterion.LogicalExpression.toSqlString(LogicalExpression.java:42)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getWhereCondition(CriteriaQueryTranslator.java:400)
at org.hibernate.loader.criteria.CriteriaJoinWalker.<init>(CriteriaJoinWalker.java:106)
at org.hibernate.loader.criteria.CriteriaJoinWalker.<init>(CriteriaJoinWalker.java:75)
at org.hibernate.loader.criteria.CriteriaLoader.<init>(CriteriaLoader.java:80)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1760)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:363)
at we.data.weref.dao.hbn.TeamDaoHbn.getTeamPlayers(TeamDaoHbn.java:109)
at we.data.weref.service.impl.TeamServiceImpl.getTeamPlayers(TeamServiceImpl.java:87)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:68)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy169.getTeamPlayers(Unknown Source)
at we.data.weref.controller.api.TeamControllerApi.getTeamPlayers(TeamControllerApi.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.authentication.www.DigestAuthenticationFilter.doFilter(DigestAuthenticationFilter.java:233)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
My hibernate criteria is as following
return getSession()
.createCriteria(TeamPlayer.class, "tp")
.createAlias("player.playerSuspensions", "ps", JoinType.LEFT_OUTER_JOIN)
.add(Restrictions.and(
Restrictions.or(
Restrictions.isNull("ps"),
Restrictions.eq("ps.team.id", teamId)
),
Restrictions.eq("tp.team.id", teamId)
)
)
.list();
#Entity
public class TeamPlayer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne
#JsonSerialize(using = IdSerializer.class)
private Team team;
#ManyToOne
#JsonSerialize(using = IdFirstNameLastNameSerializer.class)
private Player player;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
this.player = player;
}
public Team getTeam() {
return team;
}
public void setTeam(Team team) {
this.team = team;
}
}
#Entity
public class Player implements Serializable {
private static final long serialVersionUID = 5688361063269574977L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
#OneToMany(mappedBy = "player")
private List<PlayerSuspension> playerSuspensions;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
#Entity
public class PlayerSuspension implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
#ManyToOne
private Player player;
#ManyToOne
private Team team;
#ManyToOne // if competition == null then player is suspended from all the competitions
private Competition competition; // if competition given then only from that particular competition
private Date startDate;
private Integer games;
private Integer weeks;
private Integer gamesSpent;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
this.player = player;
}
public Team getTeam() {
return team;
}
public void setTeam(Team team) {
this.team = team;
}
}
ps is an alias. You should specify a property name of PlayerSuspension. For an example ps.name.
You can use something like this (you can convert it to criteria). Maybe, it can be more simply
from TeamPlayer teamPlayer
left join teamPlayer.player player
left join player.playerSuspensions suspension
where suspension.team.id = :teamId
or not exists (select innerTeamPlayer.id from TeamPlayer innerTeamPlayer
inner join innerTeamPlayer.player innerPlayer
inner join innerPlayer.playerSuspensions
where innerTeamPlayer.id = teamPlayer.id)
Update
You can't use TeamPlayer.getPlayerSuspension() with result of this HQL. Because of collections are lazy by default. You can try to fetch playerSuspensions by HQL with left join fetch
from TeamPlayer teamPlayer
left join teamPlayer.player player
left join fetch player.playerSuspensions suspension
where suspension.team.id = :teamId
or not exists (select innerTeamPlayer.id from TeamPlayer innerTeamPlayer
inner join innerTeamPlayer.player innerPlayer
inner join innerPlayer.playerSuspensions
where innerTeamPlayer.id = teamPlayer.id)
or you can change a mapping
#OneToMany(fetch = FetchType.EAGER, mappedBy = "player")
private List<PlayerSuspension> playerSuspensions;

CriteriaBuilder in JPA - where clause

Am new to JPA. Building the select query with the where clause. I need to select from table Contacts all ContactName's that equals the value of the String name.
Used the code below to create DB table:
CREATE TABLE Contacts (
ContactId BIGINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
ContactName VARCHAR(100) NOT NULL,
ContactEmailID VARCHAR(100) NOT NULL,
UserName VARCHAR(100) NOT NULL,
INDEX Contact_Names (ContactName)
) ENGINE = InnoDB;
Following is my Entity class;
#Entity
private String UserName;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ContactId")
public long getContactId() {
return ContactId;
}
public void setContactId(long contactId) {
ContactId = contactId;
}
#Basic
#Column(name = "UserName")
public String getUserName() {
return UserName;
}
public void setUserName(String UserName) {
this.UserName = UserName;
}
Following is my ContactServlet class code where i am trying to write my CriteriaBuilder code.
EntityManager manager = null;
EntityTransaction transaction = null;
try{
manager = this.factory.createEntityManager();
transaction = manager.getTransaction();
transaction.begin();
CriteriaBuilder cb = manager.getCriteriaBuilder();
CriteriaQuery<Contact> q1 = cb.createQuery(Contact.class);
Root<Contact> postRoot = q1.from(Contact.class);
q1.select(postRoot).where(cb.equal(postRoot.get("UserName"), name));
TypedQuery<Contact> qry = manager.createQuery(q1);
List<Contact> result = qry.getResultList();
for (Contact contactInstance : result)
{
DBContactName = contactInstance.getContactName().trim();
DBContactEmail = contactInstance.getContactEmailID().trim();
.....
Don't know where am i going wrong??
Following is the error while executing my project:
java.lang.IllegalArgumentException: Unable to resolve attribute [UserName] against path at org.hibernate.jpa.criteria.path.AbstractPathImpl.unknownAttribute(AbstractPathImpl.java:117) at org.hibernate.jpa.criteria.path.AbstractPathImpl.locateAttribute(AbstractPathImpl.java:214) at org.hibernate.jpa.criteria.path.AbstractPathImpl.get(AbstractPathImpl.java:185) at com.ContactServlet.doPost(ContactServlet.java:110) at javax.servlet.http.HttpServlet.service(HttpServlet.java:644) at javax.servlet.http.HttpServlet.service(HttpServlet.java:725) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:534) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658) at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745)
Try with:
q1.select(postRoot).where(cb.equal(postRoot.get("userName"), name));
The u of UserName attribute in lower case.

JPAContainer set relationship through programmatically?

I've two entities and I'm using JPAContainer but I don't know how can use to do a relationship with these 2 entities.
here my code
#Entity
#Table(name="curriculum")
public class Curriculum implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
private Long idCurriculum;
#Temporal(TemporalType.DATE)
private Date dataCad;
#Size(min=5, max=50)
#NotNull
#NotEmpty
private String nome;
#NotEmpty
private String sexo;
#Email
#NotEmpty
#NotNull
#Size(max=250)
#Column(unique=true)
private String email;
#NotNull
#NotEmpty
#Size(min=14, max=14)
#Column(unique=true)
private String cpf;
}
#Entity
#Table(name="curriculum2")
public class Curriculum2 implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
private Long idC2; //NOT NULL AUTO_INCREMENT,
#NotNull #OneToOne #JoinColumn(name="cpf")
private Curriculum curriculum; //NOT NULL,
#NotNull #Temporal(TemporalType.DATE)
private Date dataNasceu; //NOT NULL,
#NotNull #NotEmpty #Size(min=5, max=50)
private String cidade; //` varchar(50) NOT NULL,
#NotNull #NotEmpty #Size(min=5, max=50)
private String endereco; //` varchar(50) NOT NULL,
#NotNull
private int numero; //` int(11) NOT NULL,
#NotNull #NotEmpty #Size(min=5, max=50)
private String bairro; //` varchar(50) NOT NULL,
}
/** here app UI */
/** datasource */
private final CustomJPAContainer<Curriculum2> datasource = new CustomJPAContainer<Curriculum2>(Curriculum2.class);
private final CustomJPAContainer<Curriculum> dsCurriculum = new CustomJPAContainer<Curriculum>(Curriculum.class);
/** beans */
private final Curriculum2 bean = new Curriculum2();
private final Curriculum curriculum = dsCurriculum.getItem(22L).getEntity();
/** beanfieldgroup validation */
private final BeanFieldGroup<Curriculum2> binder = new BeanFieldGroup<Curriculum2>(Curriculum2.class);
public VerticalLayout buildLayout() {
//mainlayout
mainLayout = new VerticalLayout();
mainLayout.setSpacing(true);
mainLayout.setMargin(true);
//tab
tab = new TabSheet();
tab.setSizeUndefined();
mainLayout.addComponent(tab);
//tab1
vLayout_tab1 = new VerticalLayout();
vLayout_tab1.setMargin(true);
vLayout_tab1.setSpacing(true);
binder.setItemDataSource(bean);
Field<?> field = null;
//data nascimento
field = binder.buildAndBind("Data nascimento", "dataNasceu", PopupDateField.class);
dataNasceu = (PopupDateField) field;
dataNasceu.setDateFormat("dd/MM/yyyy");
vLayout_tab1.addComponent(dataNasceu);
//cidade
field = binder.buildAndBind("Cidade", "cidade", TextUpper.class);
cidade = (TextUpper) field;
cidade.setMaxLength(50);
cidade.setWidth("10cm");
vLayout_tab1.addComponent(cidade);
//endereco
field = binder.buildAndBind("Endereço", "endereco", TextUpper.class);
endereco = (TextUpper) field;
endereco.setMaxLength(50);
endereco.setWidth("10cm");
vLayout_tab1.addComponent(endereco);
//numero
field = binder.buildAndBind("Número", "numero");
numero = (TextField) field;
numero.setWidth("2cm");
numero.selectAll();
numero.addStyleName("numeros");
vLayout_tab1.addComponent(numero);
//bairro
field = binder.buildAndBind("Bairro", "bairro", TextUpper.class);
bairro = (TextUpper) field;
bairro.setWidth("10cm");
vLayout_tab1.addComponent(bairro);
}
/** exception */
15:53:19,600 DEBUG [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] - Cannot add or update a child row: a foreign key constraint fails (`ibgdb`.`curriculum2`, CONSTRAINT `FK_curriculuns2_curriculuns` FOREIGN KEY (`cpf`) REFERENCES `curriculum` (`cpf`) ON UPDATE CASCADE) [n/a]
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`ibgdb`.`curriculum2`, CONSTRAINT `FK_curriculuns2_curriculuns` FOREIGN KEY (`cpf`) REFERENCES `curriculum` (`cpf`) ON UPDATE CASCADE)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1041)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4237)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4169)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2617)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2778)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2834)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2156)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2441)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2366)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2350)
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.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at com.sun.proxy.$Proxy30.executeUpdate(Unknown Source)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2870)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3381)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:362)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:203)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:183)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:167)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:320)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:287)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:126)
at org.hibernate.ejb.event.EJB3MergeEventListener.saveWithGeneratedId(EJB3MergeEventListener.java:71)
at org.hibernate.event.internal.DefaultMergeEventListener.saveTransientEntity(DefaultMergeEventListener.java:236)
at org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:216)
at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:154)
at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:76)
at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:904)
at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:888)
at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:892)
at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:879)
at com.vaadin.addon.jpacontainer.provider.MutableLocalEntityProvider$1.run(MutableLocalEntityProvider.java:141)
at com.vaadin.addon.jpacontainer.provider.MutableLocalEntityProvider.runInTransaction(MutableLocalEntityProvider.java:120)
at com.vaadin.addon.jpacontainer.provider.MutableLocalEntityProvider.addEntity(MutableLocalEntityProvider.java:137)
at com.vaadin.addon.jpacontainer.provider.CachingMutableLocalEntityProvider.addEntity(CachingMutableLocalEntityProvider.java:164)
at com.vaadin.addon.jpacontainer.JPAContainer.addEntity(JPAContainer.java:1113)
at br.ind.ibg.views.InformacoesView.buttonClick(InformacoesView.java:328)
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 com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:508)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:198)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:161)
at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:969)
at com.vaadin.ui.Button.fireClick(Button.java:368)
at com.vaadin.ui.Button$1.click(Button.java:57)
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 com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:168)
at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:118)
at com.vaadin.server.communication.ServerRpcHandler.handleBurst(ServerRpcHandler.java:207)
at com.vaadin.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:111)
at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:91)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:37)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1382)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:238)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
15:53:19,602 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] - SQL Error: 1452, SQLState: 23000
15:53:19,602 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] - Cannot add or update a child row: a foreign key constraint fails (`ibgdb`.`curriculum2`, CONSTRAINT `FK_curriculuns2_curriculuns` FOREIGN KEY (`cpf`) REFERENCES `curriculum` (`cpf`) ON UPDATE CASCADE)
15:53:19,603 DEBUG [org.hibernate.ejb.AbstractEntityManagerImpl] - Mark transaction for rollback
15:53:19,603 DEBUG [org.hibernate.engine.transaction.spi.AbstractTransactionImpl] - rolling back
15:53:19,678 DEBUG [org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction] - rolled JDBC Connection
15:53:19,679 DEBUG [org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction] - re-enabling autocommit
How I can persist with JPAContainer these 2 entities ?
This is Hibernate 101.
For proof-of-concept this is easy. You're best bet is to use Spring transaction + hibernate + dao model

Categories