这期内容当中小编将会给大家带来有关hibernate中怎么使用configuration类配置数据库,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
提供session的hibernate工具类:
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; public class HibernateUtils1 { private static Configuration cfg = null; private static SessionFactory factory = null; private static Session session = null; static { cfg = new Configuration().setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver") .setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/aleavesystem?pinGlobalTxToPhysicalConnection=true&characterEncoding=UTF-8") .setProperty("hibernate.connection.username", "root") .setProperty("hibernate.connection.password", "root").addAnnotatedClass(Employee.class); ; factory = cfg.buildSessionFactory(new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()) .build()); } public static Session getSession() { if(factory != null) { return factory.openSession(); }else{ factory = cfg.buildSessionFactory(new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()) .build()); } return factory.openSession(); } public static void closeSession() { if(session != null && session.isOpen()){ session.close(); } } }
说明:参阅了hibernate的接口文档,org.hibernate.cfg.Configuration类提供设置property属性的方法setProperty,参数格式(属性名称,属性值),例如设置数据库连接为setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/aleavesystem?characterEncoding=UTF-8"),其他属性依次类推,可以面条式增加属性configuration.setProperty("a","1").setProperty("b","2")......
addAnnotatedClass,则是为实体类配置提供的方法,如上面代码addAnnotatedClass(Employee.class),配置注解实体类,同样也是可以面条式增加多个实体类addAnnotatedClass(类A).addAnnotatedClass(类B).addAnnotatedClass(类C),参数注意是class类,直接实体类后面加.class就行。
实体类Employee:
import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "Employee ") public class Employee { @Id @Column(name = "id") private int id; public Employee() {} public int getId() { return id; } public void setId( int id ) { this.id = id; } }
测试入口类:
import org.hibernate.*; public class Test { public static void main(String[] args) { /**** 上面是配置准备,下面开始我们的数据库操作 ******/ Session session = HibernateUtils1.getSession();// 从会话工厂获取一个session Transaction t = session.beginTransaction(); Employee e1 = new Employee(); e1.setId(1); Employee e2 = new Employee(); e2.setId(2); session.persist(e1); session.persist(e2); t.commit(); session.close(); System.out.println("successfully saved"); } }
上述就是小编为大家分享的hibernate中怎么使用configuration类配置数据库了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。