hibernate 中資料庫連線操作
阿新 • • 發佈:2018-12-19
hibernate.cfg.xml 中配置
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> //方言 <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property> <property name="connection.driver_class">oracle.jdbc.OracleDriver</property> <property name="hbm2ddl.auto">update</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.show_sql">true</property> <mapping resource="com/oracle/bean/TSalary.hbm.xml"/> <mapping resource="com/oracle/bean/TUser.hbm.xml"/> <mapping resource="com/oracle/bean/Tstudent.hbm.xml"/> <!-- DB schema will be updated if needed --> <!-- <property name="hbm2ddl.auto">update</property> --> </session-factory> </hibernate-configuration>
持久化操作
Configuration cfg = new Configuration(); cfg.configure(); SessionFactory sessionFactory = cfg.buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); TSalary salary=new TSalary(); String uuid= UUID.randomUUID().toString().replace("-",""); salary.setWorkcode(uuid); salary.setDept("業務部"); salary.setBaseSalary(new BigDecimal(10000)); session.save(salary); session.getTransaction().commit(); session.close(); sessionFactory.close();