4

I have such code:

Session session = HibernateSessionFactory.sessionFactory.openSession();

    System.out.println("------------------" + session.get(User.class, (long) 10));
    System.out.println("------------------" + session.createSQLQuery("SELECT  * FROM  diploma.tbl_users Where id = 10").addEntity(User.class).uniqueResult());

First row return null.
The second return valid record.

But if I change places:

System.out.println("------------------" + session.createSQLQuery("SELECT  * FROM  diploma.tbl_users Where id = 10").addEntity(User.class).uniqueResult());
    System.out.println("------------------" + session.get(User.class, (long) 10));

Both rows return correct result:

This is my hibernate session factory:

public class HibernateSessionFactory {

public static SessionFactory sessionFactory = new Configuration().configure("/META-INF/hibernate.cfg.xml")
        .buildSessionFactory();

 }

Why session.get(User.class, (long) 10)) return null ?

UPDATE hibernate config:

<hibernate-configuration>
<session-factory>

    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/diploma</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">password</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
    <property name="hibernate.connection.charSet">UTF-8</property>
    <property name="hibernate.hbm2ddl.auto">update</property>

    <property name="show_sql">true</property>
    <property name="format_sql">true</property>

    .........................................
    <mapping class="edu.test.entities.User" />
            ..................................

</session-factory>

User.java

@Entity
@Table(name = "tbl_Users")
public class User extends BaseEntity {

@NotEmpty
@Column(name = "Name")
private String name;

@NotEmpty
@Column(name = "Surname")
private String surname;

@NotEmpty
@Column(name = "Login")
private String login;

@NotEmpty
@Size(min=6, max=20)
@Column(name = "Password")
private String password;

@NotEmpty
@Column(name = "Email")
private String email;

@NotEmpty
@Column(name = "Phone")
private String phone;

@ManyToOne
@JoinColumn(name = "Role", nullable = false)
private Roles role;

    // getters and setters

Id field from base entity

   @MappedSuperclass
   public class BaseEntity implements Serializable {    
    @Id
@Column(name = "id", unique = true, nullable = false)
@GeneratedValue
private Long id;

UPDATE 2 The problem was in mapping file @JoinColumn(name = "Role", nullable = false) private Roles role; I have specified that Role cannot be null and the record that I have tried to retrieve with id 10 have null Role foreign key. So I change nullable = true and it works.

10
  • what is the primary key for the entity class? Commented Nov 15, 2012 at 13:06
  • @Arun how you expect to get the entity before adding it? Commented Nov 15, 2012 at 13:11
  • what did you mean 'you try to get entity before saving.' saving what ? Commented Nov 15, 2012 at 13:12
  • 2
    @Lemberg Can you share hibernate.cfg.xml and the mapping file Commented Nov 15, 2012 at 13:48
  • 1
    Hibernate: select user0_.id as id7_1_, user0_.Email as Email7_1_, user0_.Login as Login7_1_, user0_.Name as Name7_1_, user0_.Password as Password7_1_, user0_.Phone as Phone7_1_, user0_.Role as Role7_1_, user0_.Surname as Surname7_1_, roles1_.id as id6_0_, roles1_.RoleName as RoleName6_0_ from tbl_Users user0_ inner join tbl_Roles roles1_ on user0_.Role=roles1_.id where user0_.id=? Commented Nov 15, 2012 at 13:59

1 Answer 1

2

Hibernate implements Identity Map PoEAA pattern, where the Hibernate session plays the role of the map. When you call .addEntity(), the loaded entities become associated with the Hibernate session.

Then when you call Hibernate session's get method it first checks the entity cache and returns a existing entity if present.

So in the first statement when you call get the entity is not yet present in the entity map. In the second snippet the entity is being cached with .addEntity() method.

update So the problem is that reference to the role is declared with nullable = false, and there's no such a role in the database.

See also: http://martinfowler.com/eaaCatalog/identityMap.html

Sign up to request clarification or add additional context in comments.

6 Comments

you are saying that in the first row it returns null because the User entity is not declared in the hibernate.cfg file, right?
Not quite, in this code the entity is registered manually in hibernate session with the query, ok. I'll update the answer then.
I agree that retrieving single instance with SQL is not right choice I want to do this with session.get() but it doesnt work.
@Lemberg How is the id database field mapped in your class(where is the java field)?
@BorisTreukhov Can you tell me if I can retrieve User from DB with null reference to Roles?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.