hibernate主键生成策略-为什么我的程序只有native方式生效(注解)

hibernate主键生成策略-为什么我的程序只有native方式生效(注解)

问题描述:

我想采用uuid主键策略,但是多次各种尝试都不成功。我是通过往数据库插入数据测试的。重点是使用native能正常插入数据,而使用uuid就不行,主要原因是整个程序也不报错,就是运行了,看起来就像是跳过执行插入语句一样,实际上是执行到了插入方法的,也没有堆栈信息什么的可参考。代码如下:
@Id
@GeneratedValue (generator = "paymentableGenerator" )

@GenericGenerator (name = "paymentableGenerator" , strategy = "uuid" )
@Column(unique=true)
private String userId;
----------------------------------------------------------------------------------
@Test
public void testAddTest() {
com.liuz.ssh.bean.Test test = new com.liuz.ssh.bean.Test();
//test.setUserId("123");
test.setGender(1);
test.setPassword("123");
test.setUsername("1232");
try {
testService.addTest(test);
} catch (Exception e) {
e.printStackTrace();
}
}

说到底就是自己对hibernate不够了解,经过多次尝试,最终发现必须通过提交事务才能将数据保存到数据库,当然可以设置事务为自动提交什么的,这些方式大家自己尝试,这里的解决办法就是:提交事务 提交事务 提交事务;
@Id

@GeneratedValue(generator = "system-uuid")

@GenericGenerator(name = "system-uuid", strategy = "asign")

@Column(unique=true)
private String userId;
//--------------------------------------------------------
@Test
public void testAddTest() {
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:config\applicationContext.xml");

SessionFactory sessionFactory = context.getBean("sessionFactory", SessionFactory.class);

Session session = sessionFactory.openSession();

    Transaction tx = session.beginTransaction();
    com.liuz.ssh.bean.Test test = new com.liuz.ssh.bean.Test();
    test.setUserId("123");
    test.setGender(1);
    test.setPassword("123");
    test.setUsername("1232");
    try {
        session.save(test);
        //testService.addTest(test);
    } catch (Exception e) {
        e.printStackTrace();
    }
    tx.commit();

    session.clear();
}