I am looking into Hibernate and storing collections of complex types. But I run into exception.
I have the following persistent class:
public class Item {
private Long id;
private Set images = new HashSet();
private Collection<Data> data = new ArrayList<Data>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Set getImages() {
return images;
}
public void setImages(Set images) {
this.images = images;
}
public Collection<Data> getData() {
return data;
}
public void setData(Collection<Data> data) {
this.data = data;
}
}
The Data class is as follows:
public class Data {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public boolean equals(Object obj) {
if(!(obj instanceof Data) )
return false;
Data d = (Data) obj;
if(d.firstName.equals(firstName) && d.lastName.equals(lastName))
return true;
return false;
}
#Override
public int hashCode() {
int result;
result = 17;
result = 31 * result + firstName.hashCode();
result = 31 * result + lastName.hashCode();
return result;
}
The mapping files are as follows:
For Item class:
<hibernate-mapping>
<class name="com.entities.Item" table="ITEM">
<id name="id" type="java.lang.Long">
<column name="ID" />
<generator class="identity" />
</id>
<set name="images" table="ITEM_IMAGE" inverse="false" lazy="true">
<key>
<column name="ID" />
</key>
<element type="string">
<column name="IMAGES" />
</element>
</set>
<bag name="data" table="DATA" inverse="false" lazy="true">
<key>
<column name="ID" />
</key>
<one-to-many class="com.entities.Data" />
</bag>
</class>
</hibernate-mapping>
For Data class:
<hibernate-mapping>
<class name="com.entities.Data" table="DATA">
<id name="firstName" type="java.lang.String">
<column name="FIRSTNAME" />
<generator class="assigned" />
</id>
<property name="lastName" type="java.lang.String">
<column name="LASTNAME" />
</property>
</class>
</hibernate-mapping>
In my code to save data to MySQL:
Transaction tx = session.beginTransaction();
Item item = new Item();
Set images = new HashSet();
images.add("C:\\");
images.add("D:\\");
item.setImages(images);
List<Data> data = new ArrayList<Data>();
Data a = new Data();
a.setFirstName("John");
a.setLastName("Smith");
data.add(a);
item.setData(data);
session.save(item);
tx.commit();//-->Exception here
session.close();
I get the following exception on tx.commit();
Hibernate: insert into ITEM values ( ) Hibernate: insert into
ITEM_IMAGE (ID, IMAGES) values (?, ?) Hibernate: insert into
ITEM_IMAGE (ID, IMAGES) values (?, ?) Hibernate: update DATA set ID=?
where FIRSTNAME=? Hibernate: update DATA set ID=? where FIRSTNAME=?
1454 [main] ERROR org.hibernate.jdbc.AbstractBatcher - Exception
executing batch: org.hibernate.StaleStateException: Batch update
returned unexpected row count from update [0]; actual row count: 0;
expected: 1 at
org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:85)
at
org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:70)
at
org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:90)
at
org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at
org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
at
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)
at
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:188)
at
org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at
org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216) at
org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383) at
org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at com.entities.Main.main(Main.java:44)
Why do I get this exception?
If I remove the Collection<Data> data to store only the Set the code works and the data are saved in MySQL.
Note: The mapping files have been created by Eclipse Hibernate plugin.
Made the following changes to your code :
Transaction tx = session.beginTransaction();
Item item = new Item();
//added save here to attach the object to persistance context.
// (This might be optional)
session.save(item);
Set images = new HashSet();
images.add("C:\\");
images.add("D:\\");
item.setImages(images);
List<Data> data = new ArrayList<Data>();
Data a = new Data();
a.setFirstName("John");
a.setLastName("Smith");
//added save here to attach the object to persistance context.
//this is required without cascading settings
session.save(a)
data.add(a);
item.setData(data);
session.save(item);
tx.commit();//-->Exception here
session.close();
You could otherwise set appropriate the cascading options on the bag!
AFAIK you are getting the error since you are trying to persist an association without the other entity (Data) being in persistant state and the cascading options are set to none by default. Again I haven't tried out to run my piece of snippet but this will point you in the right direction.
UPDATE from the OP:
The problem is solved by using inverse="true", doing cascade and also I have to reference from Data to Item otherwise the FK column is not updated
Is it possibly due to the fact that you're adding a to the list data twice?
Related
I'm trying to create a one to many relation between two tables. TestCase has a FK called Type
Basically many testCases can have one type but a testCase can only have one type.
What am I missing here?
TestCase table
TestType table
But I'm getting
Unkown column idtestType in field list
Model
public class TestCase {
private int id;
private String name;
private TestType type;
private byte[] data;
private String creationDate;
private String createdBy;
public TestCase() {
}
public TestCase(String name, TestType type, byte[] data, String creationDate, String createdBy) {
this.name = name;
this.type = type;
this.data = data;
this.creationDate = creationDate;
this.createdBy = createdBy;
}
TestCase.xml
<hibernate-mapping>
<class name="com.atp.Model.TestCases.TestCase" table="testCases">
<meta attribute="class-description">
This class contains the testCases details.
</meta>
<id name="id" type="int" column="idtestCase">
<generator class="native"/>
</id>
<property name="name" column="name" type="string"/>
<many-to-one name="type" class="com.atp.Model.TestCases.TestType" fetch="select">
<column name="idtestType"/>
</many-to-one>
<property name="data" column="data" type="binary"/>
<property name="creationDate" column="creationDate" type="string"/>
<property name="createdBy" column="createdBy" type="string"/>
</class>
</hibernate-mapping>
Model
public class TestType {
private int id;
private String desc;
private Set<TestCase> testCases = new HashSet<>(0);
public TestType() {
}
public TestType(String desc, Set<TestCase> testCases) {
this.desc = desc;
this.testCases = testCases;
}
TestType.xml
<hibernate-mapping>
<class name="com.atp.Model.TestCases.TestType" table="testType">
<meta attribute="class-description">
This class contains the testCases details.
</meta>
<id name="id" type="int" column="idtestType">
<generator class="native"/>
</id>
<property name="desc" column="desc" type="string"/>
<set name="testCases">
<key>
<column name="idtestType" />
</key>
<one-to-many class="com.atp.Model.TestCases.TestCase" />
</set>
</class>
</hibernate-mapping>
Trying to add it to the database
public static void addTestCase(String testName, String type, MultipartFile file, String createdBy) {
byte[] data;
Date date = new Date();
final DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String creationDate = sdf.format(date);
TestType testType = new TestType();
testType.setDesc(type);
try {
data = file.getBytes();
TestCase testCase = new TestCase(testName,testType,data,creationDate,createdBy);
testType.getTestCases().add(testCase);
Database.addToDatabase(testCase);
} catch (IOException e) {
e.printStackTrace();
}
}
You're missing a
idtestType
column in the TestCase table.
Or, if you want to use the type column in the existing table your TestCase.xml-Mapping is wrong and should be
<many-to-one name="type" class="com.atp.Model.TestCases.TestType" fetch="select">
<column name="type"/>
</many-to-one>
(column is "type" instead of "idtestType")
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.
I know that it is a trite question, but I could not find a solution. I have two beans and one of them has HashMap collection. I'm getting an exception when trying to read this collection. Mapping config had been specified to load this collection eagerly.
My environment is :
Hibernate 4.2.0
mysql-connector-java 5.1.24
Also I have two beans:
public class FeaturedDoc {
private Long id;
private Map<Feature, Float> features;
public FeaturedDoc() {
features = new HashMap<Feature, Float>();
}
(getters and setters)
}
and
public class Feature {
private Long id;
private String name;
private Long internalId;
(getters and setters)
}
This beans have mapping:
<class name="Feature" table="FEATURE">
<id name="id" type="long" column="ID">
<generator class="increment"/>
</id>
<property name="name" length="255" type="string" unique="true" column="NAME" index="INDEX_NAME"/>
<property name="internalId" type="long" unique="true" not-null="false" column="INTERNAL_ID" index="INDEX_INTID"/>
<sql-insert>insert into FEATURE (NAME, INTERNAL_ID, ID) values (?, ?, ?) on duplicate key update ID = ID</sql-insert>
</class>
<class name="FeaturedDoc" table="FEATURED_DOC">
<id name="id" type="long" column="ID">
<generator class="increment"/>
</id>
<map name="features" table="DOC_FEATURE" cascade="all" lazy="false" fetch="join">
<key column="ID"></key>
<map-key-many-to-many column="FEATURE_ID" class="Feature"/>
<element column="value" type="float"/>
</map>
</class>
Also I have DAO layer with method:
public FeaturedDoc read(long id) {
FeaturedDoc fd = null;
try {
session.beginTransaction();
fd = session.get(FeaturedDoc.class, id);
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
} finally {
close();
}
return fd;
}
When I'm trying to do something like this:
FeaturedDoc fd = daoService.read(26);
System.out.println(fd.getFeatures());
I'm getting an exception
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
Do you know how should I fix this error?
Assuming that everything else is okay (in the mappings), have you tried putting lazy="false" before cascade="all". I found that this was a problem in my mapping which resulted in this LazyInitializationException error.
This ordering is shown in the following Hibernate Reference: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/collections.html
I have solved this problem! The reason was in Feature class. It had not hashCode and equals functions. After implementation of these functions everything has become ok.
I have two tables, orders and order_items. The relationship between them is One-to-Many. Order_items.fk_orders is the foreign key. Orders.ID is the primary key.
I first save the orders and then the order_items, but the order_items.fk_orders is different from the orders.ID and the order_items.fk_orders values is long(eg '3213148',but the normal value is '425618'),the problem only occurs sometimes.
Orders.hbm.xml as below:
....
<id name="id" column="ID" type="java.lang.Long">
<generator class="native">
</generator>
</id>
<set name="orderProduct" lazy="false" cascade="all"
sort="unsorted">
<key column="FK_ORDERS"></key>
<one-to-many
class="com.arvato.ecommerce.model.base.OrderItems"/>
</set>
....
OrderItem.hbm.xml as below:
....
<id name="id" column="ID" type="java.lang.Long">
<generator class="native">
</generator>
</id>
<many-to-one name="orders"
class="com.arvato.ecommerce.model.base.Orders" cascade="none"
outer-join="auto" update="true" insert="true" lazy="false"
column="FK_ORDERS"/>
....
The code as below:
//save order
Orders orders = new Orders();
....
....
orders.setOrderItems(null);//(I think it is strange I don't know why set the null value to OrderItems?)
session = getSession();
session.save(object);
session.flush()
//save order items
....
Collection orderItems = orders.getOrderItems();
if (orderItems != null) {
OrderItem orderItem;
for (Iterator itemIterator = orderItems.iterator(); itemIterator.hasNext(); orderdao.insertOrderProduct(orderItem)) {
orderItem = (OrderItem) itemIterator.next();
orderItem.setOrders(orders);
}
}
....
public int insertOrderProduct(OrderItem orderItem)
throws DaoException {
Session session =null;
try {
session = getSession();
session.save(orderItem);
session.flush();
return 1;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
Your mapping seems correct, that's the way you are using it that is wrong.
Since you use cascade="all", all the OrderItems listed in an instance of Orders will be automatically persisted when you save the Orders instance !
The below code should be enough :
Orders orders = new Orders();
orders.addItem(new OrderItem());
...
session = getSession();
session.save(object);
session.flush()
where the addItem method looks like :
public void addItem(OrderItem item) {
if (items == null) {
items = new ArrayList<OrderItem>();
}
item.setOrders(this);
items.add(item);
}
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