I want to do one-to-many mapping in hibernate,but it is showing exception,I tried a lot but unable to find solution
I have below two tables
dept
deptno -- number primary key
dname -- varchar2(10)
loc -- varchar2(10)
employee1
empno -- number primary key
username -- varchar2(10)
deptno -- number(10) foreign key
when I am not adding #Entity annotation on Dept.java class I am getting below stacktrace
21:35:11.554 [main] DEBUG o.h.i.f.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [enhanced-table] -> [class org.hibernate.id.enhanced.TableGenerator]
21:35:11.554 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
21:35:11.554 [main] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml
21:35:11.632 [main] DEBUG org.hibernate.util.DTDEntityResolver - trying to resolve system-id [http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd]
21:35:11.632 [main] WARN org.hibernate.util.DTDEntityResolver - recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
21:35:11.632 [main] DEBUG org.hibernate.util.DTDEntityResolver - attempting to resolve on classpath under org/hibernate/
21:35:11.632 [main] DEBUG org.hibernate.util.DTDEntityResolver - located [http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd] in classpath
21:35:11.663 [main] DEBUG org.hibernate.cfg.Configuration - hibernate.connection.driver_class=oracle.jdbc.driver.OracleDriver
21:35:11.663 [main] DEBUG org.hibernate.cfg.Configuration - hibernate.connection.url=jdbc:oracle:thin:#localhost:1521:XE
21:35:11.663 [main] DEBUG org.hibernate.cfg.Configuration - hibernate.connection.username=test
21:35:11.663 [main] DEBUG org.hibernate.cfg.Configuration - hibernate.connection.password=test
21:35:11.663 [main] DEBUG org.hibernate.cfg.Configuration - hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
21:35:11.663 [main] DEBUG org.hibernate.cfg.Configuration - session-factory config [null] named class [com.beans.Employee] for mapping
21:35:11.663 [main] DEBUG org.hibernate.cfg.Configuration - session-factory config [null] named class [com.beans.Dept] for mapping
21:35:11.663 [main] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null
21:35:11.663 [main] DEBUG org.hibernate.cfg.Configuration - properties: {hibernate.connection.password=test, java.runtime.name=Java(TM) SE Runtime Environment, sun.boot.library.path=C:\Program Files\Java\jdk1.7.0_17\jre\bin, java.vm.version=23.7-b01, hibernate.connection.username=test, java.vm.vendor=Oracle Corporation, java.vendor.url=http://java.oracle.com/, path.separator=;, java.vm.name=Java HotSpot(TM) 64-Bit Server VM, file.encoding.pkg=sun.io, user.script=, user.country=US, sun.java.launcher=SUN_STANDARD, sun.os.patch.level=, java.vm.specification.name=Java Virtual Machine Specification, user.dir=E:\javahyd\eclipse_new_hibernate\One_Many1, java.runtime.version=1.7.0_17-b02, java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironment, java.endorsed.dirs=C:\Program Files\Java\jdk1.7.0_17\jre\lib\endorsed, os.arch=amd64, java.io.tmpdir=C:\Users\rajeev\AppData\Local\Temp\, line.separator=
, java.vm.specification.vendor=Oracle Corporation, user.variant=, os.name=Windows 7, sun.jnu.encoding=Cp1252, java.library.path=C:\Program Files\Java\jdk1.7.0_17\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jdk1.7.0_17/bin/../jre/bin/server;C:/Program Files/Java/jdk1.7.0_17/bin/../jre/bin;C:/Program Files/Java/jdk1.7.0_17/bin/../jre/lib/amd64;C:\Windows\SYSTEM32\WBEM;C:\Program Files\Java\jdk1.7.0_17\bin;C:\ORACLEXE\APP\ORACLE\PRODUCT\10.2.0\SERVER\BIN;.;.;C:\PROGRAM FILES\MYSQL\MYSQL SERVER 5.5\BIN;C:\Program Files\WIDCOMM\Bluetooth Software\;C:\Program Files\WIDCOMM\Bluetooth Software\syswow64;C:\Program Files\Dell\DW WLAN Card;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\apache-maven-3.2.1\bin;C:\Windows\System32;.;E:\sts\sts-bundle\sts-3.6.0.M1;;., java.specification.name=Java Platform API Specification, java.class.version=51.0, sun.management.compiler=HotSpot 64-Bit Tiered Compilers, os.version=6.1, user.home=C:\Users\rajeev, user.timezone=Asia/Calcutta, java.awt.printerjob=sun.awt.windows.WPrinterJob, file.encoding=Cp1252, java.specification.version=1.7, hibernate.connection.driver_class=oracle.jdbc.driver.OracleDriver, java.class.path=E:\javahyd\eclipse_new_hibernate\One_Many1\target\classes;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\annotations-api.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\catalina-ant.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\catalina-ha.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\catalina-tribes.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\catalina.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\ecj-3.7.2.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\el-api.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\jasper-el.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\jasper.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\jsp-api.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\tomcat-api.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\tomcat-coyote.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\tomcat-dbcp.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\tomcat-i18n-es.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\tomcat-i18n-fr.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\tomcat-i18n-ja.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\tomcat-jdbc.jar;C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\tomcat-util.jar;C:\Users\rajeev\.m2\repository\ch\qos\logback\logback-core\1.1.2\logback-core-1.1.2.jar;C:\Users\rajeev\.m2\repository\ch\qos\logback\logback-classic\1.1.2\logback-classic-1.1.2.jar;C:\Users\rajeev\.m2\repository\org\slf4j\slf4j-api\1.7.6\slf4j-api-1.7.6.jar;C:\Users\rajeev\.m2\repository\com\myoracle\ojdbc14\10.2.0.1.0\ojdbc14-10.2.0.1.0.jar;C:\Users\rajeev\.m2\repository\org\hibernate\hibernate-core\3.6.10.Final\hibernate-core-3.6.10.Final.jar;C:\Users\rajeev\.m2\repository\antlr\antlr\2.7.6\antlr-2.7.6.jar;C:\Users\rajeev\.m2\repository\commons-collections\commons-collections\3.1\commons-collections-3.1.jar;C:\Users\rajeev\.m2\repository\dom4j\dom4j\1.6.1\dom4j-1.6.1.jar;C:\Users\rajeev\.m2\repository\org\hibernate\hibernate-commons-annotations\3.2.0.Final\hibernate-commons-annotations-3.2.0.Final.jar;C:\Users\rajeev\.m2\repository\org\hibernate\javax\persistence\hibernate-jpa-2.0-api\1.0.1.Final\hibernate-jpa-2.0-api-1.0.1.Final.jar;C:\Users\rajeev\.m2\repository\javax\transaction\jta\1.1\jta-1.1.jar;C:\Users\rajeev\.m2\repository\javassist\javassist\3.12.1.GA\javassist-3.12.1.GA.jar, user.name=rajeev, hibernate.bytecode.use_reflection_optimizer=false, java.vm.specification.version=1.7, sun.java.command=com.test.Test, java.home=C:\Program Files\Java\jdk1.7.0_17\jre, sun.arch.data.model=64, hibernate.dialect=org.hibernate.dialect.Oracle10gDialect, hibernate.connection.url=jdbc:oracle:thin:#localhost:1521:XE, user.language=en, java.specification.vendor=Oracle Corporation, awt.toolkit=sun.awt.windows.WToolkit, java.vm.info=mixed mode, java.version=1.7.0_17, java.ext.dirs=C:\Program Files\Java\jdk1.7.0_17\jre\lib\ext;C:\Windows\Sun\Java\lib\ext, sun.boot.class.path=C:\Program Files\Java\jdk1.7.0_17\jre\lib\resources.jar;C:\Program Files\Java\jdk1.7.0_17\jre\lib\rt.jar;C:\Program Files\Java\jdk1.7.0_17\jre\lib\sunrsasign.jar;C:\Program Files\Java\jdk1.7.0_17\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.7.0_17\jre\lib\jce.jar;C:\Program Files\Java\jdk1.7.0_17\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.7.0_17\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.7.0_17\jre\classes, java.vendor=Oracle Corporation, file.separator=\, java.vendor.url.bug=http://bugreport.sun.com/bugreport/, sun.io.unicode.encoding=UnicodeLittle, sun.cpu.endian=little, sun.desktop=windows, sun.cpu.isalist=amd64}
21:35:11.663 [main] DEBUG org.hibernate.cfg.Configuration - Preparing to build session factory with filters : {}
21:35:11.741 [main] DEBUG org.hibernate.cfg.Configuration - Processing hbm.xml files
21:35:11.741 [main] DEBUG org.hibernate.cfg.Configuration - Process annotated classes
21:35:11.756 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.beans.Employee
21:35:11.789 [main] DEBUG org.hibernate.cfg.Ejb3Column - Binding column: Ejb3DiscriminatorColumn{logicalColumnName'DTYPE', discriminatorTypeName='string'}
21:35:11.804 [main] DEBUG org.hibernate.cfg.AnnotationBinder - no value specified for 'javax.persistence.sharedCache.mode'; using UNSPECIFIED
21:35:11.820 [main] DEBUG o.h.cfg.annotations.EntityBinder - Import with entity name Employee
21:35:11.820 [main] INFO o.h.cfg.annotations.EntityBinder - Bind entity com.beans.Employee on table employee1
21:35:11.867 [main] DEBUG org.hibernate.cfg.Ejb3Column - Binding column: Ejb3Column{table=org.hibernate.mapping.Table(employee1), mappingColumn=empno, insertable=true, updatable=true, unique=false}
21:35:11.882 [main] DEBUG o.h.cfg.annotations.PropertyBinder - binding property empno with lazy=false
21:35:11.882 [main] DEBUG o.h.c.annotations.SimpleValueBinder - building SimpleValue for empno
21:35:11.882 [main] DEBUG o.h.cfg.annotations.PropertyBinder - Building property empno
21:35:11.898 [main] DEBUG org.hibernate.cfg.Ejb3Column - Binding column: Ejb3JoinColumn{logicalColumnName='deptno', referencedColumn='', mappedBy=''}
21:35:11.898 [main] DEBUG org.hibernate.cfg.Ejb3Column - Binding column: Ejb3Column{table=org.hibernate.mapping.Table(employee1), mappingColumn=dept, insertable=true, updatable=true, unique=false}
21:35:11.898 [main] DEBUG o.h.cfg.annotations.PropertyBinder - Building property dept
21:35:11.898 [main] DEBUG org.hibernate.cfg.Ejb3Column - Binding column: Ejb3Column{table=org.hibernate.mapping.Table(employee1), mappingColumn=deptno, insertable=true, updatable=true, unique=false}
21:35:11.898 [main] DEBUG o.h.cfg.annotations.PropertyBinder - binding property deptno with lazy=false
21:35:11.898 [main] DEBUG o.h.c.annotations.SimpleValueBinder - building SimpleValue for deptno
21:35:11.898 [main] DEBUG o.h.cfg.annotations.PropertyBinder - Building property deptno
21:35:11.898 [main] DEBUG org.hibernate.cfg.Ejb3Column - Binding column: Ejb3Column{table=org.hibernate.mapping.Table(employee1), mappingColumn=userName, insertable=true, updatable=true, unique=false}
21:35:11.898 [main] DEBUG o.h.cfg.annotations.PropertyBinder - binding property userName with lazy=false
21:35:11.898 [main] DEBUG o.h.c.annotations.SimpleValueBinder - building SimpleValue for userName
21:35:11.898 [main] DEBUG o.h.cfg.annotations.PropertyBinder - Building property userName
21:35:11.898 [main] DEBUG o.h.c.annotations.SimpleValueBinder - Setting SimpleValue typeName for empno
21:35:11.898 [main] DEBUG o.h.c.annotations.SimpleValueBinder - Setting SimpleValue typeName for deptno
21:35:11.898 [main] DEBUG o.h.c.annotations.SimpleValueBinder - Setting SimpleValue typeName for userName
21:35:11.898 [main] DEBUG org.hibernate.cfg.Configuration - processing fk mappings (*ToOne and JoinedSubclass)
Exception in thread "main" org.hibernate.AnnotationException: #OneToOne or #ManyToOne on com.beans.Employee.dept references an unknown entity: com.beans.Dept
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:107)
at org.hibernate.cfg.Configuration.processEndOfQueue(Configuration.java:1580)
at org.hibernate.cfg.Configuration.processFkSecondPassInOrder(Configuration.java:1503)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1419)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1856)
at com.test.Test.main(Test.java:17)
when I am adding #Entity annotation on Dept.java class I am getting below stacktrace
Exception in thread "main" org.hibernate.MappingException: Repeated column in mapping for entity: com.beans.Employee column: deptno (should be mapped with insert="false" update="false")
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:676)
at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:698)
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:720)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:474)
at org.hibernate.mapping.RootClass.validate(RootClass.java:235)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1362)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1865)
at com.test.Test.main(Test.java:17)
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:XE</property>
<property name="hibernate.connection.username">test</property>
<property name="hibernate.connection.password">test</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<mapping class="com.beans.Employee"></mapping>
<mapping class="com.beans.Dept"></mapping>
</session-factory>
</hibernate-configuration>
Dept.java
package com.beans;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class Dept {
#Id
private int deptno;
private String dname;
private String loc;
#OneToMany(mappedBy = "dept")
Set<Employee> set;
public Set<Employee> getSet() {
return set;
}
public void setSet(Set<Employee> set) {
this.set = set;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
}
Employee.java
package com.beans;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "employee1")
public class Employee {
#Id
private int empno;
private String userName;
private int deptno;
#ManyToOne
#JoinColumn(name = "deptno")
private Dept dept;
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
public int getEmpno() {
return empno;
}
public void setEmpno(int empno) {
this.empno = empno;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
}
Test.java
package com.test;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.beans.Dept;
import com.beans.Employee;
public class Test {
public static void main(String[] args) {
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Employee employee = new Employee();
Dept dept = new Dept();
Set<Employee> set = new HashSet<Employee>();
set.add(employee);
dept.setDeptno(11);
dept.setDname("mca");
dept.setLoc("sbp");
dept.setSet(set);
session.save(dept);
employee.setEmpno(1);
employee.setUserName("rajeev");
employee.setDept(dept);
session.save(employee);
transaction.commit();
session.close();
}
}
can anyone help me to find the mistake...
below is the githib link
git#github.com:mcarajeev/hibernate3.git
In your Employee.java you have added deptno as a join column and you have already added deptno as column so it is creating two deptno in same table which is giving Exception.
Solution : You can remove private int deptno from Employee.java as your Join column will work as foreign key.
Looking at the entities, this exception should not be thrown, however when I checked code on git, #Entity annotation is missing on Dept class, are you sure that you are using #Entity?
Note that this exception is thrown when you map an entity about which hibernate is not aware off. Like in your case, Employee has association with Dept but Dept is not known to hibernate as an entity as you have not used #Entity.
private int deptno;
#ManyToOne
#JoinColumn(name = "deptno")
private Dept dept;
Remove private int deptno, hibernate will generate it as a part of association.
Related
below is the error I am receiving when I run the test class given to me for the assignment:
2019-11-14T19:58:38.309Z [34mINFO [0;39m [main ] [36mc.a.cst8277.assignment3.Test[0;39m - setup JPA EntityManagerFactory, create EntityManager (Session)
2019-11-14T19:58:40.004Z [34mINFO [0;39m [main ] [36meclipselink.logging.all[0;39m - EclipseLink, version: Eclipse Persistence Services - 2.7.3.v20180807-4be1041
2019-11-14T19:58:40.021Z [34mINFO [0;39m [main ] [36meclipselink.logging.connection[0;39m - connecting(DatabaseLogin(
platform=>H2Platform
user name=> "sa"
datasource URL=> "jdbc:h2:mem:Assignment3"
))
2019-11-14T19:58:40.429Z [34mINFO [0;39m [main ] [36meclipselink.logging.connection[0;39m - Connected: jdbc:h2:mem:Assignment3
User: SA
Database: H2 Version: 1.4.199 (2019-03-13)
Driver: H2 JDBC Driver Version: 1.4.199 (2019-03-13)
2019-11-14T19:58:40.512Z [1;31mERROR[0;39m [main ] [36meclipselink.logging.all[0;39m - Exception [EclipseLink-0] (Eclipse Persistence Services - 2.7.3.v20180807-4be1041): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions:
---------------------------------------------------------
Exception [EclipseLink-46] (Eclipse Persistence Services - 2.7.3.v20180807-4be1041): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: There should be one non-read-only mapping defined for the primary key field [PORTFOLIO.PORTFOLIO_ID].
Descriptor: RelationalDescriptor(com.algonquincollege.cst8277.assignment3.model.Portfolio --> [DatabaseTable(PORTFOLIO)])
The last portion repeats for all the classes and I also get another set of errors which also repeats for all the classes I have created:
Exception [EclipseLink-41] (Eclipse Persistence Services - 2.7.3.v20180807-4be1041): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: A non-read-only mapping must be defined for the sequence number field.
Descriptor: RelationalDescriptor(com.algonquincollege.cst8277.assignment3.model.Portfolio --> [DatabaseTable(PORTFOLIO)])
Here is the test class I need to run:
/**************************************************************G*********o****o****g**o****og**joob*********************
* File: Test.java
* Course materials (19F) CST 8277
* #author Mike Norman
*
* #date 2019 10
*/
package com.algonquincollege.cst8277.assignment3;
import java.lang.invoke.MethodHandles;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.algonquincollege.cst8277.assignment3.dao.BankUserDAOImpl;
public class Test {
private static final Class<?> _thisClaz = MethodHandles.lookup().lookupClass();
private static final Logger logger = LoggerFactory.getLogger(_thisClaz);
public static final String ASSIGNMENT3_PU_NAME = "Assignment3-main-PU";
public static void main(String[] args) {
logger.info("setup JPA EntityManagerFactory, create EntityManager (Session)");
EntityManagerFactory emf = Persistence.createEntityManagerFactory(ASSIGNMENT3_PU_NAME);
EntityManager em = emf.createEntityManager();
em.close();
emf.close();
}
}
Here is one of the 8 classes in question, the error I posted specifically references this class/table but all others are setup similarly and have similar error messages:
package com.algonquincollege.cst8277.assignment3.model;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the PORTFOLIO database table.
*
*/
#Entity
#NamedQuery(name="Portfolio.findAll", query="SELECT p FROM Portfolio p")
public class Portfolio extends ModelBase implements Serializable {
private static final long serialVersionUID = 1L;
private List<Asset> assets;
public Portfolio() {
}
#Override
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="PORTFOLIO_ID", insertable=false, updatable=false)
public int getId() {
return this.id;
}
//bi-directional many-to-one association to Asset
#OneToMany(mappedBy="portfolio")
public List<Asset> getAssets() {
return this.assets;
}
public void setAssets(List<Asset> assets) {
this.assets = assets;
}
public Asset addAsset(Asset asset) {
getAssets().add(asset);
asset.setPortfolio(this);
return asset;
}
public Asset removeAsset(Asset asset) {
getAssets().remove(asset);
asset.setPortfolio(null);
return asset;
}
}
Try changing insertable to true for id field. Like this:
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="PORTFOLIO_ID", insertable=true, updatable=false)
public int getId() {
return this.id;
}
I am creating some simple Spring Boot project with Hibernate JPA.
I created some data model which consists 5 tables for now and created entities reflecting tables. I have set spring.jpa.generate-ddl=true and my entities was correctly reflected by schema created in PostgreSQL.
Next step was to start adding relations.
Part of my assumed datamodel is (paron my UML)
Very simple one to many relation.
My entities look that way (getters and setters omitted below, exist in code):
#Entity
public class AppUser {
#Id
#GeneratedValue
private long id;
private String name;
private String secondName;
private String email;
private java.util.Date joinDate;
#ManyToOne
#JoinColumn(name = "user_role_id")
private UserRole userRole;
}
#Entity
public class UserRole {
#Id
#GeneratedValue
private long id;
private String roleName;
}
I launch my application with spring.jpa.generate-ddl=true and column user_role_id gets created in AppUser table but application fails to start due errors:
2018-10-11 19:41:35.435 INFO 45564 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000228: Running hbm2ddl schema update
2018-10-11 19:41:35.466 WARN 45564 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 42703
2018-10-11 19:41:35.466 ERROR 45564 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: column t1.tgconstrname does not exist
There is full stacktrace (please advise if should paste it here instead of pastebin:
https://pastebin.com/x4qNJkK9
When I set spring.jpa.generate-ddl=false application starts succesfully.
Any ideas why is that happening?
I'm trying to get the accounts existing in a bank, but the list is empty even though the link between the two exist in the database.
Knowing that the interaction between the database and my program works fine, except that bank.getAccounts() returns an empty list.
here is my code.
What i'm trying to do is:
public class Main {
public static void main(String[] args) {
Bank bank = new Bank();
bank.setName("XXX");
bank.setStreet("XXX");
bank.setPc("XXX");
bank.save();
Account c = new account();
c.setBalance(10);
c.setBank(bank);
c.save();
account c2 = new account();
c2.setBalance(20);
c2.setBank(bank);
c2.save();
for(account c : bank.getAccounts())
System.out.println("account n°: " + c.getId() + ", balance: " + c.getBalance());
}
}
The Bank class is:
#Entity
#Table(name = "BANK")
public class Bank implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8199961750065782869L;
static private BankDAO dao;
private long id;
private String name;
private String street;
private String pc;
private Set<Account> accounts;
public Bank() {
super();
this.accounts = new HashSet<>();
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
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 String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getPc() {
return pc;
}
public void setPc(String pc) {
this.pc = pc;
}
#OneToMany(cascade = CascadeType.ALL, mappedBy="bank")
public Set<Account> getAccounts() {
return accounts;
}
public void setAccounts(Set<Account> accounts) {
this.accounts = accounts;
}
// Equals and hashCode implementations deleted
#Transient
private BankDAO getDao() {
if(Bank.dao == null)
dao = BankDAO.getDAO();
return Bank.dao;
}
public long save() {
Bank.dao = this.getDao();
return dao.save(this);
}
public int delete() {
Bank.dao = this.getDao();
return dao.delete(this);
}
}
The Accounts class code:
#Entity
#Table(name = "Account")
public class Account implements Serializable{
private static final long serialVersionUID = 7224745445343369682L;
static private AccountDAO dao;
public long id;
public int balance;
public Bank bank;
public Account() {
super();
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="bank_id", nullable=false)
#Id
public Bank getBank() {
return bank;
}
public void setBank(Bank bank) {
this.bank = bank;
}
#Transient
private AccountDAO getDao() {
if(Account.dao == null)
dao = AccountDAO.getDAO();
return Account.dao;
}
/*
* save the state of the object: save or update
* #return: the id of the object
*/
public long save() {
Account.dao = this.getDao();
return dao.save(this);
}
public int delete() {
Account.dao = this.getDao();
return dao.delete(this);
}
}
Log is:
Feb 13, 2018 11:38:54 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.12.Final}
Feb 13, 2018 11:38:54 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Feb 13, 2018 11:38:54 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
Feb 13, 2018 11:38:54 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Feb 13, 2018 11:38:55 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Feb 13, 2018 11:38:55 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost:5432/hibernateDataBase]
Feb 13, 2018 11:38:55 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=postgres, password=****}
Feb 13, 2018 11:38:55 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Feb 13, 2018 11:38:55 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Feb 13, 2018 11:38:55 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
Feb 13, 2018 11:38:55 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
Feb 13, 2018 11:38:55 PM org.hibernate.type.BasicTypeRegistry register
INFO: HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#67080771
Feb 13, 2018 11:38:55 PM org.hibernate.mapping.RootClass checkCompositeIdentifier
WARN: HHH000038: Composite-id class does not override equals(): business.Account
Feb 13, 2018 11:38:55 PM org.hibernate.mapping.RootClass checkCompositeIdentifier
WARN: HHH000039: Composite-id class does not override hashCode(): business.Account
Hibernate: alter table ACCOUNT drop constraint FKc0nxjvf82u84r0b01m367tss3Feb 13, 2018 11:38:56 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#10650953] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: drop table if exists BANK cascade
Hibernate: drop table if exists ACCOUNT cascade
Hibernate: drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start 1 increment 1
Feb 13, 2018 11:38:56 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#7db82169] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: create table BANK (id int8 not null, pc varchar(255), name varchar(255), street varchar(255), primary key (id))
Hibernate: create table ACCOUNT (id int8 not null, balance int4 not null, bank_id int8 not null, primary key (id, bank_id))
Hibernate: alter table ACCOUNT add constraint FKc0nxjvf82u84r0b01m367tss3 foreign key (bank_id) references BANK
Feb 13, 2018 11:38:56 PM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#3276732'
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into BANK (pc, name, street, id) values (?, ?, ?, ?)
Hibernate: select account_.id, account_.bank_id, account_.balance as balance2_1_ from ACCOUNT account_ where account_.id=? and account_.bank_id=?
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into ACCOUNT (balance, id, bank_id) values (?, ?, ?)
Hibernate: select account_.id, account_.bank_id, account_.balance as balance2_1_ from ACCOUNT account_ where account_.id=? and account_.bank_id=?
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into ACCOUNT (balance, id, bank_id) values (?, ?, ?)
Bank bank = new Bank();
bank.setName("XXX");
bank.setStreet("XXX");
bank.setPc("XXX");
bank.save(); -- checkpoint 1
Account c = new account();
c.setBalance(10);
c.setBank(bank); -- checkpoint 2
c.save();
account c2 = new account();
c2.setBalance(20);
c2.setBank(bank);
c2.save(); -- checkpoint 3
It wont work that way as as you can see # checkpioint 1 you have you Bank object and nothing will change its state. I gues you would like to Bank->account poulate by checkpoint 2 and 3 but this is not going to happen.
What you have to do is to put that relations manually by simply
bank.getAccounts().add(c1);
However in order to relations to work like you would expect (as bank is already initialized so no lazy fetch will occure), you need to actually fetch your bank again via eg query. Then, newly returned bank will have unitialized collections proxies and will indeed perform additional select (if not eager fetch specified) to get collections of accounts associated with that bank.
I found the problem.
i was using find(id) method to fetch the bank from the database, when i use load(id) or get(id) it works fine.
Best regards.
I'm trying to achieve second level cache in my Java EE project using Hibernate. My Hibernate version is 5.1.0.Final. I've created a table employee in my MySQL database. I've included hibernate-ehcache-4.3.5.Final.jar in my project, but it's throwing Unable to create requested service [org.hibernate.cache.spi.RegionFactory] error. Here is the hibernate.cfg.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/intu</property>
<property name="hibernate.connection.username">****</property>
<property name="hibernate.connection.password">****</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="show_sql">false</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="com.dom.Employee"/>
</session-factory>
</hibernate-configuration>
My Employee class:
package com.intu;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
#Entity
#Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
#Table(name = "employee")
public class Employee {
private int id;
private String name;
public Employee() {
}
public Employee(String name, float salary) {
super();
this.name = name;
}
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;
}
}
My Code:
package com.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.intu.Employee;
import com.util.HibernateUtil;
public class Ehcache {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(org.hibernate.Version.getVersionString());
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session1=factory.openSession();
Employee emp1=(Employee)session1.load(Employee.class,121);
System.out.println(emp1.getId()+" "+emp1.getName());
session1.close();
Session session2=factory.openSession();
Employee emp2=(Employee)session2.load(Employee.class,121);
System.out.println(emp2.getId()+" "+emp2.getName());
session2.close();
}
}
The error is
eb 23, 2016 3:10:49 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.0.Final}
Feb 23, 2016 3:10:49 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Feb 23, 2016 3:10:49 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Initial SessionFactory creation failed.org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.cache.spi.RegionFactory]
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:20)
at com.util.HibernateUtil.<clinit>(HibernateUtil.java:7)
at com.test.Ehcache.main(Ehcache.java:14)
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.cache.spi.RegionFactory]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:244)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:208)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.boot.internal.MetadataBuilderImpl$MetadataBuildingOptionsImpl.<init>(MetadataBuilderImpl.java:663)
at org.hibernate.boot.internal.MetadataBuilderImpl.<init>(MetadataBuilderImpl.java:127)
at org.hibernate.boot.MetadataSources.getMetadataBuilder(MetadataSources.java:135)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:655)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at com.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
... 2 more
Caused by: org.hibernate.HibernateException: could not instantiate RegionFactory [net.sf.ehcache.hibernate.EhCacheRegionFactory]
at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactor yInitiator.java:84)
at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactor yInitiator.java:29)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:234)
I'm not sure what exactly is missing. What should be added more to get it working?
You are using incompatible versions of EhCache and Hibernate, that leads to initialization issues. if you are using Hibernate 5.1, better to use the corresponding ehcache version to go with it:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.1.0.Final</version>
</dependency>
--Add the below line at hibernate.cfg.xml
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.internal.EhcacheRegionFactory</property>
<property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property>
The above one would solve the issue.
I'm trying to set up a web application using JBoss and Hibernate, but I can't get the SQL database running, encountering several problems.
My main problem is that when calling persist() Hibernate tries to insert an empty object into my table, the log is starting with this exception:
12:39:26,985 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (http--127.0.0.1-8080-1) HHH000228: Running hbm2ddl schema update
12:39:26,986 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (http--127.0.0.1-8080-1) HHH000102: Fetching database metadata
12:39:26,987 ERROR [org.hibernate.tool.hbm2ddl.SchemaUpdate] (http--127.0.0.1-8080-1) HHH000319: Could not get database metadata: java.sql.SQLException: You cannot set autocommit during a managed transaction!
at org.jboss.jca.adapters.jdbc.BaseWrapperManagedConnection.setJdbcAutoCommit(BaseWrapperManagedConnection.java:888)
After using Google I couldn't really figure out how to solve it, but my application continues running. Somewhere after this Hibernate seems to try to call persist() to a created object.
12:39:27,202 INFO [stdout] (http--127.0.0.1-8080-1) Hibernate:
12:39:27,202 INFO [stdout] (http--127.0.0.1-8080-1) insert
12:39:27,203 INFO [stdout] (http--127.0.0.1-8080-1) into
12:39:27,203 INFO [stdout] (http--127.0.0.1-8080-1) Person
12:39:27,203 INFO [stdout] (http--127.0.0.1-8080-1) (id, birthdate, gender, name, password)
12:39:27,204 INFO [stdout] (http--127.0.0.1-8080-1) values
12:39:27,204 INFO [stdout] (http--127.0.0.1-8080-1) (null, ?, ?, ?, ?)
Using Logger I saw that this Person object is correctly created, but as you can see Hibernate sees the values as (null, ?, ?, ?, ?).
After this this exception is thrown:
12:39:27,218 ERROR [org.apache.tapestry5.ioc.Registry] (http--127.0.0.1-8080-1) org.hibernate.exception.ConstraintViolationException: integrity constraint violation: NOT NULL check constraint; SYS_CT_10031 table: PERSON column: ID
So then, my persistence.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="facePlace">
<non-jta-data-source>java:jboss/facePlace</non-jta-data-source>
<class>webtech2.faceplace.entities.Person</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
The relevant code is:
#Inject
#Persistence
EntityManager em;
public boolean signUp(String name,
String password,
String repeatPassword,
Date birthdate,
String gender) {
if (!password.equals(repeatPassword)) {
return false;
}
log.info("person data: " + name + " " + password + " " + repeatPassword + " " + birthdate.toString() + " " + gender);
String saltedPassword = hashText + password;
String hashedPassword = generateHash(saltedPassword);
em.getTransaction().begin();
Person xperson = new Person(name, hashedPassword, birthdate, gender);
em.persist(xperson);
em.getTransaction().commit();
return true;
}
My entity looks like:
#Entity
public class Person implements Serializable {
private String name;
private Date birthdate;
private long id;
private String password;
private String gender;
private Set<Person> friends;
#Id
#GeneratedValue
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
So I'm not an expert with all this, someone sees some shit in there?
Looks like your primary key is not being set when hibrenate saves the file. the #Id column in your #Entity should specify a primary key generation strategy, rather than leaving #GeneratedValue without any paramaters and having hibernate trying to pick a default generation startegy.
If you are using an identity column in the database you set.
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="pkey")
private Integer pkey;