DL1997
2017-10-15 10:48
采纳率: 33.3%
浏览 1.2k

hibernate的session.save()为什么没有执行

User 是一个有id username passwrod的类
hb.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">



<!-- 先配置数据库链接信息 -->
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/dxlin
root
duanlin113
none
<!-- 数据库方言 -->
org.hibernate.dialect.MySQLDialect


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">



<!-- 主键生成策略 -->



</class>
</hibernate-mapping>
Test 类

package com.dxlin.hibtest;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import com.dxlin.pojo.User;

public class Test {
public static void main(String args[]) {
System.out.println("1");
//1.新建立Configuration对象
Configuration cfg = new Configuration();
cfg.configure("hb.cfg.xml");
System.out.println("2");
//2.通过Configuration新建sessionFactory对象
ServiceRegistry registry = new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties())
.build();
SessionFactory sf = cfg.buildSessionFactory(registry);
System.out.println("3");
//3.通过sessionFactory得到session
Session session = sf.openSession();
System.out.println("4");
//4.通过session对象得到Transaction对象
Transaction tx = session.beginTransaction();
System.out.println("5");
//保存数据
User user = new User();
user.setUsername("DL2");
user.setPassword("002");
session.save(user);
System.out.println("6");
//提交事务

    tx.commit();
    System.out.println("7");
    //关闭session
    session.close();
    System.out.println("8");
} 

}
代码不报错,运行为
图片说明

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • ID F 2019-10-24 09:36

    我遇见过,是因为我的主键生成策略是native但是主键手动添加了,改成assigned就行了

    打赏 评论

相关推荐 更多相似问题