I have problem with my project. My apache derby generate id, in table it works. But in app it doesnt work. In derby I set id autoincrement (start with 1, increment by 1), but i get this error:
> Caused by: ERROR 42Z23 : An attempt was made to modify the identity
> column ' ID'
.
My entity:
package com.springapp.mvc.models;
import javax.persistence.*;
#Entity
#Table(name = "USERS", schema = "KK", catalog = "")
public class UsersEntity {
private int id;
private String name;
private String password;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "PASSWORD")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UsersEntity that = (UsersEntity) o;
if (id != that.id) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
if (password != null ? !password.equals(that.password) : that.password != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (password != null ? password.hashCode() : 0);
return result;
}
}
hibernate xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:derby://localhost:1527/MyDB</property>
<property name="connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.DerbyDialect</property>
<!-- <property name="hbm2ddl.auto">update</property>
Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<mapping resource="mapping.xml"/>
<mapping class="com.springapp.mvc.models.AccountEntity"/>
<mapping class="com.springapp.mvc.models.BookEntity"/>
<mapping class="com.springapp.mvc.models.UsersEntity"/>
</session-factory>
</hibernate-configuration>
mapping.xml
<?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-3.0.dtd">
<hibernate-mapping>
<class name="com.springapp.mvc.models.AccountEntity" table="ACCOUNT" schema="KK">
<id name="id" column="ID"/>
<property name="name" column="NAME"/>
<property name="accountprefix" column="ACCOUNTPREFIX"/>
<property name="accountnumber" column="ACCOUNTNUMBER"/>
<property name="bankcode" column="BANKCODE"/>
<property name="userid" column="USERID"/>
</class>
<class name="com.springapp.mvc.models.BookEntity" table="BOOK" schema="KK">
<id name="id" column="ID"/>
<property name="title" column="TITLE"/>
<property name="description" column="DESCRIPTION"/>
<property name="userid" column="USERID"/>
</class>
<class name="com.springapp.mvc.models.UsersEntity" table="USERS" schema="KK">
<id name="id" column="ID"/>
<property name="name" column="NAME"/>
<property name="password" column="PASSWORD"/>
</class>
</hibernate-mapping>
Thanks
If you set the ID table field to auto-increment then you should not try to insert an id because this is auto generated by derby.
or use Hibernate to generate you id
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
If you define your table this way (either with the GENERATED BY DEFAULT or GENERATED AS ALWAYS keywords)
CREATE TABLE Consultation (id INTEGER PRIMARY KEY NOT NULL GENERATED BY DEFAULT
AS IDENTITY (START WITH 1, INCREMENT BY 1),
Patient_id CHAR(10) NOT NULL REFERENCES PATIENT(CARDNUMBER),
Consultation_date CHAR(20))
you cannot directly insert anything into id. You get this error when you try to do so. You insert data into an Identity field like this:
INSERT INTO CONSULTATION (PATIENT_ID, CONSULTATION_DATE) VALUES ('B2345', '4-8-2016')
This way, the id field is autogenerated for you and incremented when ever you populate a new column.
Note I copied the sql statements above from console in Intellij, to use in a java class, add String concatenation as appropriate:
statement.executeUpdate("INSERT INTO Consultation (PATIENT_ID, CONSULTATION_DATE) VALUES " +
"('2345', '4-8-2016')");
Related
I am migrating entity mapping from an annotations app to hbm.xml
I error this error and not found the solution. Thanks
java.lang.Exception: Not an entity: class com.enterprise.package.user.domain.User
I have hibernate.cfg.xml in the resources folder, User.hbm.xml in one package and User.class in another
User.hbm.xml
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.enterprise.package.role.domain.User" table="user">
<id name="id" type="java.lang.Long">
<column name="id" />
<generator class="identity" />
</id>
<property name="username" column="username" type="java.lang.String" unique="true"/>
<property name="password" column="password" type="java.lang.String"/>
<many-to-one name="role" column="role_id" class="com.enterprise.package.role.domain.Role" not-null="true"/>
</class>
</hibernate-mapping>
User.class
public final class User {
private Long id;
private String username;
private String password;
private Role role;
public User() {
}
public User(Long id) {
this.id = id;
}
public User(Long id, String username, String password, Role role) {
this.id = id;
this.username = username;
this.password = password;
this.role = role;
}
...
}
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.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/db</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">**</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="show_sql">true</property>
<mapping package="com/enterprise/package/user/infrastructure/persistence/hibernate/Role.hbm.xml"/>
<mapping package="com/enterprise/package/user/infrastructure/persistence/hibernate/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I think the package of User class may be wrong in User.hbm.xml (we cant see in your snippet the package of this class)...
In User.hbm.xml instead of
com.enterprise.package.role.domain.User
may be
com.enterprise.package.user.domain.User.
This is my first Hibernate Application Program. I got this error when executing the main class.I Am trying to insert new record at the table student. Also it is good to say that hibernate doing the connection to the database without any problem !I keep getting this MappingException:
Hibernate: drop table if exists student
Hibernate: create table student (student_id integer not null auto_increment, First_Name varchar(255), Last_Name varchar(255), Age integer, primary key (student_id))
Dec 22, 2015 10:04:44 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Exception in thread "main" org.hibernate.MappingException: Unknown entity: org.hibernate.internal.SessionImpl
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1146)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1358)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:116)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:206)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:191)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:683)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:675)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:671)
at biztime.Manager.main(Manager.java:23)
Does anyone have any ideas as I've looked at so many duplicates but the resolutions don't appear to work for me.This is my cfg.xml
My hibernate.cfg.xml
<!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="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/anwardb</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
<mapping resource="biztime/student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
My student.java
package biztime;
public class student
{
private int student_id;
private String First_Name;
private String Last_Name;
private int Age;
public int getStudent_id()
{
return student_id;
}
public void setStudent_id(int student_id)
{
this.student_id = student_id;
}
public String getFirst_Name()
{
return First_Name;
}
public void setFirst_Name(String first_Name)
{
First_Name = first_Name;
}
public String getLast_Name()
{
return Last_Name;
}
public void setLast_Name(String last_Name)
{
Last_Name = last_Name;
}
public int getAge()
{
return Age;
}
public void setAge(int age)
{
Age = age;
}
}
student.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 package="biztime">
<class name="student" table="student ">
<id name="student_id" column="student_id">
<generator class="native"/>
</id>
<property name="First_Name" >
<column name="First_Name"/>
</property>
<property name="Last_Name">
<column name="Last_Name"/>
</property>
<property name="Age">
<column name="Age"/>
</property>
</class>
</hibernate-mapping>
I call it using this main:
Manager.java
package biztime;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Manager
{
public static void main(String[] args)
{
Configuration con=new Configuration();
con.configure();
SessionFactory sf=con.buildSessionFactory();
Session s1=sf.openSession();
student s=new student ();
s.setFirst_Name("hello");
s.setLast_Name("test");
s.setStudent_id(1);
s.setAge(20);
s1.beginTransaction();
s1.save(s1);
s1.getTransaction().commit();
s1.flush();
s1.close();
System.out.println("done");
}
}
You're attempting to save s1 which is a Session. Save s instead, which is a student (and capitalize your classnames).
I don't think you should set student_id, as it is an auto_increment field. Try removing this line: s.setStudent_id(1);
I'm currently working on a GWT + Hibernate project which should work together on an already defined and filled database. I receive an
com.google.gwt.user.client.rpc.SerializationException
when I query the database.
Here are my objects...
Database:
-- Table: asset
CREATE TABLE IF NOT EXISTS asset
(
isin VARCHAR(12) NOT NULL,
mic_code VARCHAR(4) NOT NULL DEFAULT 'n.a.',
name VARCHAR(255) NOT NULL,
type_id VARCHAR(36) NOT NULL,
PRIMARY KEY (isin, mic_code),
INDEX(isin, mic_code),
FOREIGN KEY (type_id) REFERENCES asset_type(id)
)ENGINE=InnoDB;
-- Table: asset_type
CREATE TABLE IF NOT EXISTS asset_type
(
id VARCHAR(36) NOT NULL,
type VARCHAR(40) NOT NULL,
PRIMARY KEY (id)
)ENGINE=InnoDB;
Asset.java:
public class Asset implements Serializable {
private String isin;
private String mic_code;
private String name;
private AssetType assetType;
public Asset() {
super();
}
...
AssetType.java
public class AssetType implements Serializable {
private String id;
private String type;
public AssetType() {
}
and finally the hibernate xml files:
Asset.hbm.xml
<hibernate-mapping>
<class name="com.mygwtproject.shared.model.Asset" table="ASSET">
<id name="isin" type="java.lang.String" access="field">
<column name="ISIN" />
<generator class="native" />
</id>
<property name="mic_code" type="java.lang.String" access="field">
<column name="MIC_CODE" />
</property>
<property name="name" type="java.lang.String" access="field">
<column name="NAME" />
</property>
<many-to-one name="assetType" class="com.mygwtproject.shared.model.types.AssetType" column="TYPE_ID" cascade="all" not-null="true"/>
</class>
</hibernate-mapping>
AssetType.hbm.xml
<hibernate-mapping>
<class name="com.mygwtproject.shared.model.types.AssetType" table="ASSET_TYPE">
<id name="id" type="java.lang.String" column="ID">
<generator class="native" />
</id>
<property name="type" type="java.lang.String" column ="TYPE" />
</class>
</hibernate-mapping>
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<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/asset_db</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<mapping resource="com/mygwtproject/shared/model/Asset.hbm.xml" />
<mapping resource="com/mygwtproject/shared/model/types/AssetType.hbm.xml" />
</session-factory>
</hibernate-configuration>
from log:
Hibernate:
select
assettype0_.ID as ID1_1_0_,
assettype0_.TYPE as TYPE2_1_0_
from
ASSET_TYPE assettype0_
where
assettype0_.ID=?
09:43:09,139 TRACE BasicBinder:81 - binding parameter [1] as [VARCHAR] - [ee5bb49a-dc95-403a-9f77-864a9c342f25]
09:43:09,142 TRACE BasicExtractor:78 - extracted value ([TYPE2_1_0_] : [VARCHAR]) - [Stock]
Starting Jetty on port 8888
[WARN] Exception while dispatching incoming RPC call
com.google.gwt.user.client.rpc.SerializationException: Type 'com.mygwtproject.shared.model.types.AssetType_$$_jvst77c_0' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized.: instance = com.mygwtproject.shared.model.types.AssetType#7d617ac9
so there is something wrong with my Asset -> AssetType mapping, but i cant find it. Any help is appreciated. thanks
edit:
mysql> select * from asset_type where id = 'ee5bb49a-dc95-403a-9f77-864a9c342f25';
returns
+--------------------------------------+-------+
| id | type |
+--------------------------------------+-------+
| ee5bb49a-dc95-403a-9f77-864a9c342f25 | Stock |
+--------------------------------------+-------+
1 row in set (0.00 sec)
Solution from here:
1. Create counterpart Data Transfer Objects and replace the hibernate objects.
AssetDTO.java
public class AssetDTO implements Serializable {
private String isin;
private String mic_code;
private String name;
private AssetTypeDTO assetType;
public AssetDTO() {
super();
}
public AssetDTO(String isin, String mic_code, String name,
AssetTypeDTO assetType) {
super();
this.isin = isin;
this.mic_code = mic_code;
this.name = name;
this.assetType = assetType;
}
//incl. Getter + Setter
}
AssetTypeDTO.java
public class AssetTypeDTO implements Serializable {
private String id;
private String type;
public AssetTypeDTO() {
super();
}
public AssetTypeDTO(String id, String type) {
super();
this.id = id;
this.type = type;
}
//incl. Getter + Setter
}
2. Add a new constructor to the hibernate objects.
Asset.java
...
public Asset(AssetDTO dto) {
this.isin = dto.getIsin();
this.mic_code = dto.getMic_code();
this.name = dto.getName();
AssetTypeDTO assetTypeDTO = dto.getAssetType();
if (assetTypeDTO != null) {
this.assetType = new AssetType(assetTypeDTO.getId(),
assetTypeDTO.getType());
}
}
...
AssetType.java
public AssetType(AssetTypeDTO dto) {
this.id = dto.getId();
this.type = dto.getType();
}
3. Modify your GWT RPC components.
Replace the Hibernate objects in
IService.java
public List<Asset> getAssets();
with the DTOs.
public List<AssetDTO> getAssets();
IServiceAsync.java
public void getAssets(AsyncCallback<List<Asset>> callback);
with
public void getAssets(AsyncCallback<List<AssetDTO>> callback);
4. Modify your service implementation.
ServiceImpl.java
...
#Override
public List<AssetDTO> getAssets() {
...
Query q = session.createQuery("from Asset");
List<Asset> assets = new ArrayList<Asset>(q.list());
List<AssetDTO> assetsDto = new ArrayList<AssetDTO>();
if (assets != null) {
for (Asset asset : assets) {
assetsDto.add(createAssetDTO(asset));
}
}
session.getTransaction().commit();
return assetsDto;
}
public AssetDTO createAssetDTO(Asset asset) {
AssetTypeDTO assetTypeDto = new AssetTypeDTO(asset.getAssetType()
.getId(), asset.getAssetType().getType());
AssetDTO result = new AssetDTO(asset.getIsin(), asset.getMicCode(),
asset.getName(), assetTypeDto);
return result;
}
...
5. Move the Hibernate objects (Asset, AssetType) to the server package, move the DTOs (AssetDTO, AssetTypeDTO) to the shared package and update the path in your Hibernate xml files.
How can I create (if I can) a template file for my hbm.xml files to use while they are being created from JAVA class?
I am using Jboss Hibernate Tools 3.5.1 and Eclipse Indigo
You can find a detailed description below.
Thanks for your help.
My JAVA classes are coded carefully to represent the sql table. they all have the same syntax.
for instance lets say I have the following table in my db:
Tests (id int primary key, TestData varchar(255), Type int)
a class referring to this table is:
public class TestData {
int id;
String testData;
int type;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTestData() {
return testData;
}
public void setTestData(String testData) {
this.testData = testData;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
When I create an automated hbm.xml file for this class it comes out as:
<?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 12.Ara.2013 12:33:42 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.entegrator.framework.persistent.TestData" table="TESTDATA">
<id name="id" type="int">
<column name="ÝD" />
<generator class="assigned" />
</id>
<property name="testData" type="java.lang.String">
<column name="TESTDATA" />
</property>
<property name="type" type="int">
<column name="TYPE" />
</property>
</class>
</hibernate-mapping>
as you can see, my first problem is encoding.
what else I want to do is
property column names and class table name should be converted appropriately
id generator class should be "identity"
You have to change them manually if you are creating hbm file using eclipse.
Other options are you can use annotations or create files our own to remove this extra headache.!!!
you can get more about the same at Hibernate
i have three entity and Main(User) enitiy is in relation with other two entity,how can i retrive list of three entities from database in one query using hibernate
package hib.test;
import java.util.HashSet;
import java.util.Set;
public class Country {
private Integer id;
private String country;
private Set<User> userList = new HashSet<User>();
public Country() {
super();
// TODO Auto-generated constructor stub
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Set<User> getUserList() {
return userList;
}
public void setUserList(Set<User> userList) {
this.userList = userList;
}
}
User.java
package hib.test;
public class User {
private Integer id;
private UserType userType;
private Country country;
public User() {
super();
// TODO Auto-generated constructor stub
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public UserType getUserType() {
return userType;
}
public void setUserType(UserType userType) {
this.userType = userType;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
}
UserType.java
package hib.test;
import java.util.HashSet;
import java.util.Set;
public class UserType {
private Integer id;
private String userType;
private Set<User> userList = new HashSet<User>();
public UserType() {
super();
// TODO Auto-generated constructor stub
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public Set<User> getUserList() {
return userList;
}
public void setUserList(Set<User> userList) {
this.userList = userList;
}
}
country.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">
<!-- Generated Jun 6, 2012 1:12:01 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="hib.test.Country" table="COUNTRY">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="assigned" />
</id>
<property name="country" type="java.lang.String">
<column name="COUNTRY" />
</property>
<set name="userList" table="USER" inverse="false" lazy="true">
<key>
<column name="ID" />
</key>
<one-to-many class="hib.test.User" />
</set>
</class>
</hibernate-mapping>
user.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">
<!-- Generated Jun 6, 2012 1:12:01 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="hib.test.User" table="USER">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="assigned" />
</id>
<many-to-one name="userType" class="hib.test.UserType" fetch="join">
<column name="USERTYPE" />
</many-to-one>
<many-to-one name="country" class="hib.test.Country" fetch="join">
<column name="COUNTRY" />
</many-to-one>
</class>
</hibernate-mapping>
usertype.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">
<!-- Generated Jun 6, 2012 1:12:01 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="hib.test.UserType" table="USERTYPE">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="assigned" />
</id>
<property name="userType" type="java.lang.String">
<column name="USERTYPE" />
</property>
<set name="userList" table="USER" inverse="false" lazy="true">
<key>
<column name="ID" />
</key>
<one-to-many class="hib.test.User" />
</set>
</class>
</hibernate-mapping>
How can i retrive List<User>, List<Country> and List<UserType> with one query
EDIT
public static List<UserType> getUserTypeList() {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
List<UserType> list = null;
try {
transaction = session.beginTransaction();
list = session.createQuery("from UserType as u").list();
if (list != null) {
for (UserType uType : list)
Hibernate.initialize(uType.getUserList());
}
transaction.commit();
} catch (Exception e) {
if (transaction != null)
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
return list;
}
Actually I have 1 JTable and Two combo box each for UserType and Country
So when i select any data in combo box JTable data should be filter according to selected value and in memory it shoud be save selected UserType and Country object.
if you want relational data at once and memory is not an issue, do lazy="false"
try defining fetch type to EAGER on you user mapping, that way when you load your user it will load the country and userType.
You need three queries to do that:
select u from User u;
select ut from UserType ut;
select c from Country c;
EDIT:
If what you actually want is a list of all the user types, with the users of each user type, and the country of each user of each user type, all this loaded in a single query, then you need fetch joins, as explained in the Hibernate documentation:
select userType from UserType userType
left join fetch userType.users user
left join fetch user.country