1,在MYEclpse中,新建以后,MyEclipse-->Project Facets[Capabilities]---->Instal hbernate faces,选择版本,最高,
2,User.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">
<!--
ORM
class name="hiber01.domain.User"user catalog
-->
<hibernate-mapping package="hiber01.domain">
<!-- class name指的是类名 对应的table 对应哪个数据库的表 用catalog -->
<class name="User" table="user" catalog="jd">
<!-- id的主键生成策略 name指定User类中的id字段 type指的是id的类型 -->
<id name="id" type="java.lang.Integer">
<!-- 与jd数据库中的user表中的id对应 -->
<column name="id" />
<!-- 主键的生成策略 -->
<generator class="native" />
</id>
<!-- 属性property标签配置 name指定User类中的name字段,type指定类型 -->
<property name="name" type="java.lang.String">
<!-- column 指定jd库中table表中的name字段length长度 unique是否唯一 -->
<column name="name" length="50" />
</property>
<property name="age" type="java.lang.Integer">
<column name="age" />
</property>
</class>
</hibernate-mapping>
3,新建junit 测试
package hiber01.util;
import hiber01.domain.User;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
public class UserTest {
@Test
public void test() {
Session session=HibernateSessionFactory.getSession();
User entity=(User) session.get(User.class, 2);
System.out.println(entity.toString());
session.close();
}
@Test
public void load(){
System.out.println("xxxx");
Session session=HibernateSessionFactory.getSession();
User entity=(User) session.load(User.class, 2);
System.out.println(entity.toString());
session.close();
}
@Test
public void save(){
Session session=HibernateSessionFactory.getSession();
Transaction ts=session.getTransaction();
ts.begin();
User entity=(User) session.save("wangsan", 20);
System.out.println(id);
ts.commit();
session.close();
}
@Test
public void update(){
Session session=HibernateSessionFactory.getSession();
User entity=(User) session.load(User.class, 3);
entity.setName("zhao");
Transaction ts=session.getTransaction();
ts.begin();
session.update(entity);
ts.commit();
session.close();
}
@Test
public void delete(){
Session session=HibernateSessionFactory.getSession();
User entity=(User) session.load(User.class, 3);
Transaction ts=session.getTransaction();
ts.begin();
session.update(entity);
ts.commit();
session.close();
}
}