在Eclipse中使用Hibernate
安装 Hibernate Tools 插件
https://tools.jboss.org/downloads/
Add the following URL to your Eclipse 4.13 (2019-09) installation, via:
Help > Install New Software… > Work with:
http://download.jboss.org/jbosstools/photon/stable/updates/
Then select the individual features that you want to install:
点击Next
点击Next
同意相关协议,点击Finish .
则会开始下载安装。
视网络速度,可能需要几分钟到十几分钟的时间才能完成安装。
最后会提示重启Eclipse才能生效。
在Eclipse中新建Hibernate应用
File->New -> Java Project
点击Finish
项目结构图
在Eclipse中新建用户库
此时下面显示了已经建立的用户库列表
我们要添加Hibernate的依赖库,因此点击用户库
Hibernate_4.3.5_final
选择jar文件
项目结构图
继续配置Hibernate
最后自动形成 如下的文件内容:[本例使用oracle数据库]
Oracle 11g xe 在windows安装请看如下链接:
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="hibernate.connection.password">123456</property> <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <property name="hibernate.connection.username">test</property> <property name="hibernate.default_schema">test</property> <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property> </session-factory> </hibernate-configuration>
再增加几个属性
配置文件更新后的内容如下: 注意要去掉name属性 更改 为
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory > <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="hibernate.connection.password">123456</property> <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:xe:orcl</property> <property name="hibernate.connection.username">test</property> <property name="hibernate.default_schema">test</property> <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="hibernate.show_sql">true</property> <!-- 第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据 model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等 应用第一次运行起来后才会。 --> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.default_entity_mode">pojo</property> </session-factory> </hibernate-configuration>
继续完善工程Hibernate_demo_001
新建一个包:mytest001.demo
在包mytest001.demo之下新建一个PO类: Emp
package mytest001.demo; public class Emp { // 员工的标识属性 private Integer id; // 姓名 private String name; // 年龄 private Integer age; // 工资 (分) private Integer salary; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Integer getSalary() { return salary; } public void setSalary(Integer salary) { this.salary = salary; } @Override public String toString() { return "Emp [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + "]"; } }
此刻此PO Emp.java 尚不具备持久化能力。下面为其添加注解。
@Entity 注解声明该类是一个Hibernate持久化类
@Table 指定该类映射的表,对应的数据库表名是T_EMP
@Id 指定该类的标识属性,映射到数据库的主键列
@GeneratedValue(strategy=GenerationType.SEQUENCE) 指定了主键生成策略,由于本文使用Oracle Database, 因此指定了使用 SEQUENCE
在hibernate.cfg.xml中增加持久化映射类名
增加一个新类:EmpManager,用于管理员工。
package mytest001.demo; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.Service; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; public class EmpManager { public static void main(String[] args) throws Exception { //实例化配置 Configuration configuration = new Configuration() //不带参数则默认加载hibernate.cfg.xml .configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); SessionFactory sFactory = configuration.buildSessionFactory(serviceRegistry); //创建session Session session = sFactory.openSession(); //开始事务 Transaction tx = session.beginTransaction(); //创建员工对象 Emp emp = new Emp(); // 设置员工信息 emp.setAge(28); emp.setName("scott"); emp.setSalary(10000); session.save(emp); // 提交事务 tx.commit(); session.close(); sFactory.close(); } }
最后配置文件的内容:hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory > <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="hibernate.connection.password">123456</property> <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <property name="hibernate.connection.username">test</property> <property name="hibernate.default_schema">test</property> <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="hibernate.show_sql">true</property> <!-- 第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据 model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等 应用第一次运行起来后才会。 --> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.default_entity_mode">pojo</property> <mapping class="mytest001.demo.Emp"/> </session-factory> </hibernate-configuration>
Emp.java
package mytest001.demo; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="T_EMP") public class Emp { // 员工的标识属性 @Id @GeneratedValue(strategy=GenerationType.SEQUENCE) private Integer id; // 姓名 private String name; // 年龄 private Integer age; // 工资 (分) private Integer salary; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Integer getSalary() { return salary; } public void setSalary(Integer salary) { this.salary = salary; } @Override public String toString() { return "Emp [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + "]"; } }
最后的工程结构如下:
运行EmpManger
十一月 23, 2019 8:50:47 上午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit> INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final} 十一月 23, 2019 8:50:47 上午 org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {4.3.5.Final} 十一月 23, 2019 8:50:47 上午 org.hibernate.cfg.Environment <clinit> INFO: HHH000206: hibernate.properties not found 十一月 23, 2019 8:50:47 上午 org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode provider name : javassist 十一月 23, 2019 8:50:47 上午 org.hibernate.cfg.Configuration configure INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml 十一月 23, 2019 8:50:47 上午 org.hibernate.cfg.Configuration getConfigurationInputStream INFO: HHH000040: Configuration resource: /hibernate.cfg.xml 十一月 23, 2019 8:50:47 上午 org.hibernate.cfg.Configuration doConfigure INFO: HHH000041: Configured SessionFactory: null 十一月 23, 2019 8:50:47 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!) 十一月 23, 2019 8:50:47 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH000401: using driver [oracle.jdbc.driver.OracleDriver] at URL [jdbc:oracle:thin:@localhost:1521:xe] 十一月 23, 2019 8:50:47 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH000046: Connection properties: {user=test, password=****} 十一月 23, 2019 8:50:47 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH000006: Autocommit mode: false 十一月 23, 2019 8:50:47 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure INFO: HHH000115: Hibernate connection pool size: 20 (min=1) 十一月 23, 2019 8:50:48 上午 org.hibernate.dialect.Dialect <init> INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect 十一月 23, 2019 8:50:48 上午 org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService INFO: HHH000399: Using default transaction strategy (direct JDBC transactions) 十一月 23, 2019 8:50:48 上午 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init> INFO: HHH000397: Using ASTQueryTranslatorFactory 十一月 23, 2019 8:50:48 上午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute INFO: HHH000228: Running hbm2ddl schema update 十一月 23, 2019 8:50:48 上午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute INFO: HHH000102: Fetching database metadata 十一月 23, 2019 8:50:48 上午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute INFO: HHH000396: Updating schema 十一月 23, 2019 8:50:48 上午 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata INFO: HHH000262: Table not found: T_EMP 十一月 23, 2019 8:50:48 上午 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata INFO: HHH000262: Table not found: T_EMP 十一月 23, 2019 8:50:48 上午 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata INFO: HHH000262: Table not found: T_EMP 十一月 23, 2019 8:50:48 上午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute INFO: HHH000232: Schema update complete Hibernate: select test.hibernate_sequence.nextval from dual Hibernate: insert into test.T_EMP (age, name, salary, id) values (?, ?, ?, ?) 十一月 23, 2019 8:50:48 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop INFO: HHH000030: Cleaning up connection pool [jdbc:oracle:thin:@localhost:1521:xe]
到数据库中查询表:(这个表会被自动创建)
select * from t_emp;
如果再次运行会增加新的记录。
至此,本文完成。