Hibernate初步.
一.创建一个Maven工程
引入依赖
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.0.7.Final</version> </dependency> <dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId> <version>1.1</version> </dependency>
编辑配置文件
<?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="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> <property name="connection.username">wy</property> <property name="connection.password">root</property> <!-- 数据库方言 --> <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <!-- 连接池数量 --> <property name="connection.pool_size">10</property> <!-- 开启session与线程绑定 --> <property name="current_session_context_class">thread</property> <!-- 是否在控制台打印sql --> <property name="show_sql">true</property> <!-- 创建数据库的方式 --> <property name="hbm2ddl.auto">update</property> <property name="javax.persistence.validation.mode">none</property> <!--关联的映射文件--> <mapping resource="cn/hibernate/entity/Student.hbm.xml" /> </session-factory> </hibernate-configuration>
编辑实体类
package cn.hibernate.entity; public class Student { private Integer id; private String name; 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; } }
编辑映射文件
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.hibernate.entity"> <class name="Student" table="student" > <id name="id" column="id"> <generator class="native"/> </id> <property name="name" column="name"></property> </class> </hibernate-mapping>