Hibernate实战——不使用配置文件 本是古典 何须时尚 2021-07-24 12:35 410阅读 0赞 **一 创建数据库hibernate** **二 领域模型** package org.crazyit.app.domain; import javax.persistence.*; @Entity @Table(name="news_inf") public class News { // 消息类的标识属性 @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; // 消息标题 private String title; // 消息内容 private String content; // id的setter和getter方法 public void setId(Integer id) { this.id = id; } public Integer getId() { return this.id; } // title的setter和getter方法 public void setTitle(String title) { this.title = title; } public String getTitle() { return this.title; } // content的setter和getter方法 public void setContent(String content) { this.content = content; } public String getContent() { return this.content; } } **三 测试代码** package lee; import org.hibernate.*; import org.hibernate.cfg.*; import org.hibernate.service.*; import org.hibernate.boot.registry.*; import org.crazyit.app.domain.*; public class NewsManager { public static void main(String[] args) throws Exception { // 实例化Configuration,不加载任何配置文件 Configuration conf = new Configuration() // 通过addAnnotatedClass()方法添加持久化类 .addAnnotatedClass(org.crazyit.app.domain.News.class) // 通过setProperty设置Hibernate的连接属性。 .setProperty("hibernate.connection.driver_class" , "com.mysql.jdbc.Driver") .setProperty("hibernate.connection.url" , "jdbc:mysql://localhost/hibernate") .setProperty("hibernate.connection.username" , "root") .setProperty("hibernate.connection.password" , "32147") .setProperty("hibernate.c3p0.max_size" , "20") .setProperty("hibernate.c3p0.min_size" , "1") .setProperty("hibernate.c3p0.timeout" , "5000") .setProperty("hibernate.c3p0.max_statements" , "100") .setProperty("hibernate.c3p0.idle_test_period" , "3000") .setProperty("hibernate.c3p0.acquire_increment" , "2") .setProperty("hibernate.c3p0.validate" , "true") .setProperty("hibernate.dialect" , "org.hibernate.dialect.MySQL5InnoDBDialect") .setProperty("hibernate.hbm2ddl.auto" , "update"); // 以Configuration实例创建SessionFactory实例 ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(conf.getProperties()).build(); SessionFactory sf = conf.buildSessionFactory(serviceRegistry); // 实例化Session Session sess = sf.openSession(); // 开始事务 Transaction tx = sess.beginTransaction(); // 创建消息实例 News n = new News(); // 设置消息标题和消息内容 n.setTitle("疯狂Java联盟成立了"); n.setContent("疯狂Java联盟成立了," + "网站地址http://www.crazyit.org"); // 保存消息 sess.save(n); // 提交事务 tx.commit(); // 关闭Session sess.close(); } } **四 运行结果** ![watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2NoZW5ncWl1bWluZw_size_16_color_FFFFFF_t_70][] [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2NoZW5ncWl1bWluZw_size_16_color_FFFFFF_t_70]: /images/20210724/675020dd712e4c598aa9983024ff246c.png
还没有评论,来说两句吧...