Hibernate 4.3无法在session.load()

时间:2018-06-28 14:54:06

标签: java hibernate lazy-loading

根据休眠文档,session.load(PersonEntity.class,“ 4”)将返回代理类以支持延迟加载。

但是对于我来说,它不返回任何代理类。

   //main method
        Properties properties=new Properties();
        properties.setProperty("hibernate.connection.driver_class   ", "com.mysql.jdbc.Driver");
        properties.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/person?zeroDateTimeBehavior=convertToNull");
        properties.setProperty("hibernate.connection.username", "root");
        properties.setProperty("hibernate.connection.password", "12345");
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");
        properties.setProperty("hibernate.show_sql", "true");

        Configuration configuration=new Configuration();
        configuration.setProperties(properties);
        configuration.addPackage("com.test.Entity");
        configuration.addAnnotatedClass(PersonEntity.class);

        SessionFactory sessionFactory=configuration.buildSessionFactory();

        Session session=sessionFactory.openSession();

        PersonEntity entity=new PersonEntity();
        entity.setName("Vaibhav");
        entity.setGender("M");
        entity.setAge("20");
        entity.setSex("Done");

        org.hibernate.Transaction tx=session.beginTransaction();
        //session.persist(entity);
        //session.save(entity);

        System.out.println(entity.getClass().getName());
        //entity.setSex("NOt"); 

        tx.commit();
        session.flush();

        entity=(PersonEntity) session.load(PersonEntity.class, "4");
        System.out.println(entity.getClass().getName());
        // this should fire a query to the database
        System.out.println(entity.getAge());
        session.close();


        sessionFactory.close();

这是我要保留到数据库中的类

PersonEntity类

@Entity
@Table(name="person")
@Proxy(lazy=true)
public final class PersonEntity {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="p_id")
    //@SequenceGenerator(name="test", sequenceName="seq_name")
    private String id;

    @Column(name="p_name")
    private String name;

    @Column(name="p_age")
    private String age;

    @Column(name="p_gender")
    private String gender;


    private String sex;

}

输出

com.test.Entity.PersonEntity
    Hibernate: select personenti0_.p_id as p_id1_0_0_, personenti0_.p_age as p_age2_0_0_, personenti0_.p_gender as p_gender3_0_0_, personenti0_.p_name as p_name4_0_0_, personenti0_.sex as sex5_0_0_ from person personenti0_ where personenti0_.p_id=?
    com.test.Entity.PersonEntity
问:Hibernate 4.X如何支持延迟加载? 按照规则session.load()必须返回代理类,但是当我使用getClass()。getName()检查时,它仅返回类的名称。

0 个答案:

没有答案