搭建hibernate

来源:互联网 发布:如何做免费网络推广 编辑:程序博客网 时间:2024/06/04 19:05

一.引入hibernate所需jar包


二.配置hibernate.cfg.xml

1.从hibernate.3中找到这个dtd,复制头文件,并配置数据库连接信息



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 连接数据库 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myelec?useUnicode=true&amp;characterEncoding=utf8</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">67903319</property>
<!-- 其他配置 -->
<!-- 映射文件 -->
<mapping resource="com/dream/domain/ElecText.hbm.xml"/>
</session-factory>
</hibernate-configuration>

2.创建实体类

3.创建映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
    <class name="com.domain.ElecText"  table="electest">
    <id name="textId" type="string" column="textId">
    <generator class="uuid"></generator>
    </id>
    <property name="textDate" type="date" column="textDate"></property>
    <property name="textRemark" type="string" column="textRemark"></property>
   <property name="textName" type="string" column="textName"></property>
    </class>
    </hibernate-mapping>



四.测试

package com.junit;
import java.util.Date;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import org.junit.Test;
import com.domain.ElecText;
public class HibernateTest {
@Test
public void save(){
Configuration cf=new Configuration();
cf.configure();
SessionFactory sf=cf.buildSessionFactory();
Session session=sf.openSession();
Transaction tr=session.beginTransaction();
ElecText elecText=new ElecText();
elecText.setTextDate(new Date());
elecText.setTextName("测试7.10");
elecText.setTextRemark("测试备注7.10");
session.save(elecText);
tr.commit();
session.close();

}
}



原创粉丝点击