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="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 数据库地址 --> <property name="connection.url">jdbc:mysql://127.0.0.1:3306/hibernate</property> <!-- 用户名 --> <property name="connection.username">root</property> <!-- 密码 --> <property name="connection.password"></property> <!-- 默认连接池(一般不再生产环境中使用) --> <property name="connection.pool_size">1</property> <!-- 数据库方言 --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- session管理 --> <property name="current_session_context_class">thread</property> <!-- 使用Unicode访问数据库--> <property name="connection.useUnicode">true</property> <!-- 连接数据库时数据的传输字符集编码方式 --> <property name="connection.characterEncoding">UTF-8</property> <!--是否显示sql --> <property name="show_sql">true</property> <!-- 是否自动见表或更改表结构 --> <property name="hbm2ddl.auto">update</property> <!-- hbm.xml文件 --> <mapping resource="com/hibernate/model/event.hbm.xml"/> </session-factory> </hibernate-configuration>
hibernate工具类:私有静态常量,只被初始化一次
import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory SessionFactory=intSessionFactory(); private static SessionFactory intSessionFactory(){ return new Configuration().configure().buildSessionFactory(); } public static SessionFactory getSessionFactory(){ return SessionFactory; } }
实体类:
import java.util.Date; public class Event { private Long id; private String title; private Date date; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
hbm.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <!-- class对应实体类 table对应数据库表明 --> <class name="com.hibernate.model.Event" table="envent"> <!-- name表示实体类属性id column表示对应的数据字段名 id标签表示数据库主键 --> <id name="id" column="id"> <!-- generator 表示主键生成策略 --> <generator class="native"/> </id> <!-- type表示对应数据字段类型 --> <property name="date" type="timestamp" column="createDate"/> <property name="title"/> </class> </hibernate-mapping>
使用idea 创建mavne项目junit测试的时候找不到hbm.xml文件;需要再pom.xml文件中添加下面这段代码
<build> <!--maven工程打包找不到hbm文件--> <resources> <resource> <directory>src/main/java</directory> </resource> </resources> </build>