Hibernate message that table is not mapped though it is - java

I have this table in mysql:
CREATE TABLE IF NOT EXISTS `realEstate`.`USER` (
`userID` INT NOT NULL AUTO_INCREMENT,
`username` VARCHAR(45) NULL,
`password` VARCHAR(45) NULL,
`registrationDate` VARCHAR(15) NULL,
`name` VARCHAR(45) NULL,
`surname` VARCHAR(45) NULL,
`phone` VARCHAR(45) NULL,
`email` VARCHAR(45) NULL,
`registered` TINYINT(1) NULL,
PRIMARY KEY (`userID`),
UNIQUE INDEX `user_id_UNIQUE` (`userID` ASC))
ENGINE = InnoDB;
and I try to get all its contents with hibernate. Althoug I implemented the .hbm file I get the error that the USER is not mapped[from USER]. Here how I make the question:
List<Users> users = null;
Session session = null;
Transaction transaction = null;
try {
SessionFactory factory = HibernateUtil.getSessionFactory();
session = factory.getCurrentSession();
transaction = session.beginTransaction();
Query query = session.createQuery("from USER");
users = query.list();
transaction.commit();
} catch (HibernateException ex) {
System.out.println("Exception:");
System.out.println(ex.getMessage());
if (transaction != null) {
transaction.rollback();
}
} finally {
/*for(Users user:users){
System.out.println(user.getName());
}*/
}
System.out.println("Complete");
and here is the users.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Users" table="USER">
<id name="userID" type="int">
<column name="userID" />
<generator class="assigned" />
</id>
<property name="username" type="java.lang.String">
<column name="username" length="45"/>
</property>
<property name="password" type="java.lang.String">
<column name="password" length="45" />
</property>
<property name="name" type="java.lang.String">
<column name="name" length="45"/>
</property>
<property name="date" type="java.lang.String">
<column name="registrationDate" length="45"/>
</property>
<property name="surname" type="java.lang.String">
<column name="surname" length="45"/>
</property>
<property name="phone" type="java.lang.String">
<column name="phone" length="45"/>
</property>
<property name="email" type="java.lang.String">
<column name="email" length="45"/>
</property>
<property name="registered" type="boolean">
<column name="registered" />
</property>
</class>
</hibernate-mapping>
Eveyrything seems fine to me, but it doesn't work. Can you help me?
Here's the class Users:
public class Users {
private int user_id;
private String username;
private String password;
private String date;
private String name;
private String surname;
private String phone;
private String email;
private boolean registered;
public int getuserID() {
return user_id;
}
public void setuserID(int user_id) {
this.user_id = user_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean getRegistered() {
return registered;
}
public void setRegistered(boolean registered) {
this.registered = registered;
}
}
here's the hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="session1">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/realestate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<mapping resource="users.hbm.xml"/>
<mapping resource="adminstrator.hbm.xml"/>
</session-factory>
</hibernate-configuration>
and here's the directory

In the HQL , you should use the java class name and property name of the mapped Entity instead of the actual table name and column name , so the HQL should be :
Query query = session.createQuery("from USERS");
as provided by you in users.hbm.xml

Related

hibernate unknown entity when using hibernate 5 java 8

when i want to save my object it throws unknown entity exception.
tnx in advance
Exception in thread "main" org.hibernate.MappingException: Unknown
entity: com.simpleProgrammer.User at
org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:618)
at
org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1595)
at
org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
at
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at
org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at
org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:667)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:659) at
org.hibernate.internal.SessionImpl.save(SessionImpl.java:654) at
com.simpleProgrammer.Program.main(Program.java:22)
my hibernate.cfg.xml file is here
<?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.cj.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/protein_tracker</property>
<property name="hibernate.connection.username">root</property>
<!-- <property name="hibernate.default_schema"></property> -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping resource="com/simpleProgrammer/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
my User.hbm.xml mapping file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping">
<hibernate-mapping>
<class name="com.simpleProgrammer.User" table="USERS">
<id name="id" type="int" column="id">
<generator class="identity" />
</id>
<property name="name" column="NAME" type="string" />
<component name="proteinData">
<property name="total" column="TOTAL" type="int" />
<property name="goal" column="GOAL" type="int" />
</component>
<set name="history" table="USER_HISTORY">
<key column="ID"/>
<composite-element class="com.simpleProgrammer.UserHistory">
<property name="entryTime" type="date" column="ENTRY_TIME"/>
<property name="entry" type="string" column="ENTRY"/>
</composite-element>
</set>
</class>
</hibernate-mapping>
my progaram.java
package com.simpleProgrammer;
import java.util.Date;
import org.hibernate.Session;
public class Program {
public static void main(String[] args) {
Session session = new HibernateUtilities().getSessionFactory().openSession();
System.out.println("Session Opened!!!");
session.beginTransaction();
System.out.println("Transaction begined!");
User user = new User();
user.setName("Joe");
user.getHistory().add(new UserHistory(new Date(), "Setting Name to Joe"));
user.getProteinData().setGoal(250);
user.getHistory().add(new UserHistory(new Date(), "Setting Goal to 250!"));
System.out.println("Setting user Object");
session.save(user);
System.out.println("Saving user object on table");
session.getTransaction().commit();
System.out.println("Transaction Commited!");
session.beginTransaction();
User loadedUser = session.get(User.class, 1);
System.out.println(loadedUser.getName());
System.out.println(loadedUser.getProteinData().getGoal());
System.out.println(loadedUser.getProteinData().getTotal());
loadedUser.getProteinData().setTotal(loadedUser.getProteinData().getTotal() + 50);
loadedUser.getHistory().add(new UserHistory(new Date(), "Added 50 Protein!"));
for (UserHistory history : loadedUser.getHistory()) {
System.out.println(history.getEntryTime().toString() + " " + history.getEntry());
}
session.getTransaction().commit();
session.close();
System.out.println("Session Closed!!!");
HibernateUtilities().getSessionFactory().close();
System.out.println("Session Factory Closed");
}
}
user class
package com.simpleProgrammer;
import java.util.HashSet;
import java.util.Set;
public class User {
private int id;
private String name;
private ProteinData proteinData = new ProteinData();
private Set<UserHistory> history = new HashSet<UserHistory>();
public Set<UserHistory> getHistory() {
return history;
}
public void setHistory(Set<UserHistory> history) {
this.history = history;
}
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 ProteinData getProteinData() {
return proteinData;
}
public void setProteinData(ProteinData proteinData) {
this.proteinData = proteinData;
}
}
here is my project structure
I think you should check your other configure file."Unknown entity" means your application doesn't find something like User.hbm.xml in the path.

Hibernate in Eclipse - Reverse engineering

I’m trying to use hibernate in eclipse IDE, I have reverse engineered POJO class successfully. But it shows an error in hibernate configuration under session factory.
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">1234</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/customer</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping class="com.example.pojo.Customer"/>
<mapping resource="com/example/pojo/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hibernate.reveng.xml
<?xml version="1.0" encoding="UTF-8"?>
<hibernate-reverse-engineering>
<table-filter match-catalog="customer" match-name="customer" />
<table catalog="customer" name="customer">
<column name="id"></column>
<column name="firstName"></column>
<column name="cuscol"></column>
<column name="lastName"></column>
<column name="birthDate"></column>
<column name="email"></column>
</table>
</hibernate-reverse-engineering>
Customer Pojo
public class Customer implements java.io.Serializable {
private int id;
private String firstName;
private String cuscol;
private String lastName;
private Date birthDate;
private String email;
public Customer() {
}
public Customer(int id) {
this.id = id;
}
public Customer(int id, String firstName, String cuscol, String lastName, Date birthDate, String email) {
this.id = id;
this.firstName = firstName;
this.cuscol = cuscol;
this.lastName = lastName;
this.birthDate = birthDate;
this.email = email;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getCuscol() {
return this.cuscol;
}
public void setCuscol(String cuscol) {
this.cuscol = cuscol;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getBirthDate() {
return this.birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
}
customer.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Jul 20, 2016 4:45:13 PM by Hibernate Tools 4.0.0 -->
<hibernate-mapping>
<class name="Customer" table="customer" catalog="customer">
<id name="id" type="int">
<column name="id" />
<generator class="assigned" />
</id>
<property name="firstName" type="string">
<column name="firstName" length="45" />
</property>
<property name="cuscol" type="string">
<column name="cuscol" length="45" />
</property>
<property name="lastName" type="string">
<column name="lastName" length="45" />
</property>
<property name="birthDate" type="date">
<column name="birthDate" length="10" />
</property>
<property name="email" type="string">
<column name="email" length="45" />
</property>
</class>
</hibernate-mapping>
Update mapping entry in customer.hbm.xml like this -
<class="com.example.pojo.Customer" table= "customer"/>

Hibernate Mapping Exception class not found

I'm working for several hours on this issue about hibernate mapping. I think the error could be a simple syntax mistake but I can't find it!!!
I ran into the following exception when I executed my code:
Initial SessionFactory creation failed.org.hibernate.MappingException: entity class not found: LegalFee
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.plm.dao.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:33)
at com.plm.dao.util.HibernateUtil.getSessionFactory(HibernateUtil.java:39)
at com.plm.dao.AppTest.main(AppTest.java:15)
Firstly, I'm using hibernate 4.2 with Java 8 and MariaDB 10.
See all configurations below.
My hibernate.cfg.xml, I removed C3P0 configuration:
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name='connection.driver_class'>com.mysql.jdbc.Driver</property>
<property name='connection.url'>jdbc:mysql://localhost:3306/PokerLeagueManager</property>
<property name='connection.username'>root</property>
<property name='connection.password'>mypassword</property>
<property name="show_sql">true</property>
<!-- SQL dialect -->
<property name='dialect'>org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name='show_sql'>true</property>
<mapping resource="mappings/BlindStructure.hbm.xml"/>
<mapping resource="mappings/Tournament.hbm.xml"/>
<mapping resource="mappings/LegalFee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The error is on LegalFee bean so focus on it.
See the sql table creation of legalFee:
CREATE TABLE `legalFee` (
`idFee` int(11) NOT NULL,
`shortName` varchar(50) NOT NULL,
`description` varchar(200) DEFAULT NULL,
`feePercent` int(11) DEFAULT NULL,
`feeFixed` int(11) DEFAULT NULL,
PRIMARY KEY (`idFee`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The class :
public class LegalFee implements Serializable {
/**
* generated serial uid
*/
private static final long serialVersionUID = -2259355205530727294L;
private int idFee;
private String shortName;
private String description;
private Integer feePercent;
private Integer feeFixed;
private Set<Tournament> tournaments = new HashSet<Tournament>(0);
public LegalFee() {
}
public LegalFee(int idFee, String shortName) {
this.idFee = idFee;
this.shortName = shortName;
}
public LegalFee(int idFee, String shortName, String description,
Integer feePercent, Integer feeFixed, Set<Tournament> tournaments) {
this.idFee = idFee;
this.shortName = shortName;
this.description = description;
this.feePercent = feePercent;
this.feeFixed = feeFixed;
this.tournaments = tournaments;
}
public int getIdFee() {
return this.idFee;
}
public void setIdFee(int idFee) {
this.idFee = idFee;
}
public String getShortName() {
return this.shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getFeePercent() {
return this.feePercent;
}
public void setFeePercent(Integer feePercent) {
this.feePercent = feePercent;
}
public Integer getFeeFixed() {
return this.feeFixed;
}
public void setFeeFixed(Integer feeFixed) {
this.feeFixed = feeFixed;
}
public Set<Tournament> getTournaments() {
return this.tournaments;
}
public void setTournaments(Set<Tournament> tournaments) {
this.tournaments = tournaments;
}
}
And lastly the LegalFee.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="LegalFee" table="legalFee" catalog="PokerLeagueManager" optimistic-lock="version">
<id name="idFee" type="int">
<column name="idFee" />
<generator class="identity" />
</id>
<property name="shortName" type="string">
<column name="shortName" length="50" not-null="true" />
</property>
<property name="description" type="string">
<column name="description" length="200" />
</property>
<property name="feePercent" type="java.lang.Integer">
<column name="feePercent" />
</property>
<property name="feeFixed" type="java.lang.Integer">
<column name="feeFixed" />
</property>
<set name="tournaments" table="tournament" inverse="true" lazy="true" fetch="select">
<key>
<column name="legalFee_feeId" />
</key>
<one-to-many class="Tournament" />
</set>
</class>
</hibernate-mapping>
Thanks for your help.
If your LegalFee class is not in default package you need to provide the fully classified name of the class.
e.g "class name="com.abc.xyx.LegalFee" table="legalFee" "

HSQL - HIBERNATE. org.hibernate.HibernateException: identifier of an instance of "....Author.class" was altered from 1 to null

Can't insert data to HSQL DB (in-memory). Please, help me to understand mistake, text from console:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
insert
into
author
(ID, NAME, COUNTRY)
values
(default, ?, ?)
Hibernate:
insert
into
book
(ID, NAME, GENRE, AUTHORID)
values
(default, ?, ?, ?)
Hibernate:
insert
into
book
(ID, NAME, GENRE, AUTHORID)
values
(default, ?, ?, ?)
org.hibernate.HibernateException: identifier of an instance of com.maven.vaadin.bookshelf.Author was altered from 1 to null
at org.hibernate.event.def.DefaultFlushEntityEventListener.checkId(DefaultFlushEntityEventListener.java:85)
at org.hibernate.event.def.DefaultFlushEntityEventListener.getValues(DefaultFlushEntityEventListener.java:190)
at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:147)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:219)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:99)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:375)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
at com.maven.vaadin.bookshelf.DBManager.save(DBManager.java:50)
at com.maven.vaadin.bookshelf.MyVaadinUI.init(MyVaadinUI.java:43)
at com.vaadin.ui.UI.doInit(UI.java:614)
at com.vaadin.server.communication.UIInitHandler.getBrowserDetailsUI(UIInitHandler.java:223)
at com.vaadin.server.communication.UIInitHandler.synchronizedHandleRequest(UIInitHandler.java:73)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:37)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1371)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:238)
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.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:99)
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:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
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:744)
Hibernate:
select
author0_.ID as ID0_,
author0_.NAME as NAME0_,
author0_.COUNTRY as COUNTRY0_
from
author author0_
List size: 0
Hibernate config of connection to DB and links to mapping files
<hibernate-configuration>
<session-factory>
<!-- Database connection settings, Connect to HSQL, IN Memory -->
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:mem:test</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property><property name="format_sql">true</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!--create the database schema on startup if required -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/maven/vaadin/bookshelf/Author.hbm.xml"/>
<mapping resource="com/maven/vaadin/bookshelf/Book.hbm.xml"/>
</session-factory>
Hibernate mapping files. First:
<hibernate-mapping package="com.maven.vaadin.bookshelf">
<class name="com.maven.vaadin.bookshelf.Author" table="author">
<id name="id" type="java.lang.Long">
<column name="ID" />
<generator class="native" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="64" not-null="true" unique="true" />
</property>
<property name="country" type="java.lang.String">
<column name="COUNTRY" length="32" not-null="true" />
</property>
<set name="authorbook" table="book" cascade="all" inverse="true">
<key column="AUTHORID" not-null="true" />
<one-to-many class="com.maven.vaadin.bookshelf.Book" />
</set>
</class>
Second:
<hibernate-mapping package="com.maven.vaadin.bookshelf">
<class name="com.maven.vaadin.bookshelf.Book" table="book">
<id name="id" type="java.lang.Long">
<column name="ID" />
<generator class="native" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="32" not-null="true" />
</property>
<property name="genre" type="java.lang.String">
<column name="GENRE" length="32" not-null="true" />
</property>
<many-to-one name="author" class="com.maven.vaadin.bookshelf.Author" not-null="true">
<column name="AUTHORID" />
</many-to-one>
</class>
Javas:
public class Author implements Serializable{
private Long id;
private String name;
private String country;
private Set<Book> authorbook = new HashSet<Book>();
public Author(String name, String country, Set<Book> authorBook){
super();
this.name = name;
this.country = country;
this.authorbook = authorbook;
}
public Author(){}
public void setId(Long Id){this.id = id;}
public Long getId(){return id;}
public void setName(String name){this.name = name;}
public String getName(){return name;}
public void setCountry(String country){this.country = country;}
public String getCountry(){return country;}
public void setAuthorbook(Set<Book> authorBook){this.authorbook = authorBook;}
public Set<Book> getAuthorbook(){return authorbook;}
public void addBook(Book book){
book.setAuthor(this);
this.authorbook.add(book);
}}
public class Book implements Serializable{
private Long id;
private String name;
private String genre;
private Author author;
public Book(String name, String genre){
super();
this.name = name;
this.genre = genre;
}
public Book(){}
public void setId(Long id){this.id = id;}
public Long getId(){return id;}
public void setName(String name){this.name = name;}
public String getName(){return name;}
public void setGenre(String genre){this.genre = genre;}
public String getGenre(){return genre;}
public void setAuthor(Author author){this.author = author;}
public Author getAuthor(){return author;}}
public class DBManager {
public static void main(String[] args){
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
DBManager app = new DBManager();
app.save("Author","Country");
app.list();
}
public void save(String authorName, String authorCountry){
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Long id = null;
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Author author = new Author();
author.setName(authorName);
author.setCountry(authorCountry);
Book bk1 = new Book();
Book bk2 = new Book();
bk1.setName("Book1");;
bk1.setGenre("Genre1");
bk2.setName("Book2");;
bk2.setGenre("Genre2");
author.addBook(bk1);
author.addBook(bk2);
session.save(author);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public void list() {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
#SuppressWarnings("unchecked")
List<Author> list = session.createQuery("FROM Author").list();
System.out.println("List size: " + (list).size());
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Author author = (Author) iterator.next();
}
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}}
Problem in your setter method of property id. You passed Id and not id (I is in upper case)-for which hibernate throwing the exception
You should change the setter method parameter name from Id to id, it will work.
public void setId(Long id) {
this.id = id;
}
Even if you changed from this.id = id to this.id = Id it will also work.
public void setId(Long Id) {
this.id = Id;
}

hibernate returning null objects

i am new in using hibernate and for some reason i am getting a list of null objects when i am using the following code:
public static void main(String args[])
{
Session s = HibernateUtil.currentSession();
ArrayList lst = (ArrayList) s.createQuery("from Users").list();
for(Object obj : lst){
Users user = (Users)obj;
System.Out.println(user.getUserid()); // null
}
}
my hibernate mapping xml looks like this:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Dec 27, 2012 9:48:45 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="us.Users" table="USERS">
<id name="userid" type="int">
<column name="USERID" precision="9" scale="0" />
<generator class="assigned" />
</id>
<property name="username" type="string">
<column name="USERNAME" length="200" />
</property>
<property name="password" type="string">
<column name="PASSWORD" length="200" />
</property>
<property name="firstName" type="string">
<column name="FIRST_NAME" length="200" />
</property>
<property name="lastName" type="string">
<column name="LAST_NAME" length="200" />
</property>
<property name="dateOfBirth" type="timestamp"> // my guess was that the problem appears with the timestamp property
<column name="DATE_OF_BIRTH" />
</property>
<property name="registrationDate" type="timestamp">
<column name="REGISTRATION_DATE" />
</property>
<one-to-one name="administrators" class="assignment2.Administrators"></one-to-one>
<set name="histories" table="HISTORY" inverse="true" lazy="false" fetch="select">
<key>
<column name="USERID" precision="9" scale="0" not-null="true" />
</key>
<one-to-many class="us.History" />
</set>
<set name="loginlogs" table="LOGINLOG" inverse="true" lazy="false" fetch="select">
<key>
<column name="USERID" precision="9" scale="0" not-null="true" />
</key>
<one-to-many class="us.Loginlog" />
</set>
</class>
here is my hibernate.cfg.xml :
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">abcd</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="hibernate.connection.username">SYSTEM</property>
<property name="hibernate.default_schema">SYSTEM</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.search.autoregister_listeners">false</property>
<mapping resource="assignment2/History.hbm.xml" />
<mapping resource="assignment2/Similarity.hbm.xml" />
<mapping resource="assignment2/Loginlog.hbm.xml" />
<mapping resource="assignment2/Users.hbm.xml" />
<mapping resource="assignment2/Administrators.hbm.xml" />
<mapping resource="assignment2/Mediaitems.hbm.xml" />
</session-factory>
and the users class:
/**
* Users generated by hbm2java
*/
public class Users implements java.io.Serializable {
private int userid;
private String username;
private String password;
private String firstName;
private String lastName;
private Date dateOfBirth;
private Date registrationDate;
private Administrators administrators;
private Set<History> histories = new HashSet<History>(0);
private Set<Loginlog> loginlogs = new HashSet<Loginlog>(0);
public Users() {
}
public Users(int userid) {
this.userid = userid;
}
public Users(int userid, String username, String password,
String firstName, String lastName, Serializable dateOfBirth,
Serializable registrationDate, Administrators administrators,
Set<History> histories, Set<Loginlog> loginlogs) {
this.userid = userid;
this.username = username;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
this.registrationDate = registrationDate;
this.administrators = administrators;
this.histories = histories;
this.loginlogs = loginlogs;
}
public int getUserid() {
return this.userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getDateOfBirth() {
return this.dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public Date getRegistrationDate() {
return this.registrationDate;
}
public void setRegistrationDate(Date registrationDate) {
this.registrationDate = registrationDate;
}
public Administrators getAdministrators() {
return this.administrators;
}
public void setAdministrators(Administrators administrators) {
this.administrators = administrators;
}
public Set<History> getHistories() {
return this.histories;
}
public void setHistories(Set<History> histories) {
this.histories = histories;
}
public Set<Loginlog> getLoginlogs() {
return this.loginlogs;
}
public void setLoginlogs(Set<Loginlog> loginlogs) {
this.loginlogs = loginlogs;
}
}
thanks alot in advance

Categories