1、创建数据库的表、实体类及映射文件;
(1)创建数据库表UserInfoTable:
CREATE TABLE `userinfotable` (
`ID` int(11) NOT NULL,
`NAME` varchar(255) DEFAULT NULL,
`PASSWORD` varchar(255) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
(2)创建和数据库表对应的实体类,User类;
package com.my.bean;
public class User
{
private int id;
private String username;
private String password;
... getter/setter方法 ...
}
(3)映射文件的配置;
<?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 name="com.my.bean.User" table="UserInfoTable">
<id name="id" type="int" column="ID">
<generator class="increment"/>
</id>
<property name="username" type="string" column="NAME"/>
<property name="password" type="string" column="PASSWORD"/>
</class>
</hibernate-mapping>
2、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="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/mvc_link</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<mapping resource="com/my/bean/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
3、使用hibernate插入数据到数据库中
package com.my.dao;
import com.my.bean.User;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class UserDaoImpl
{
@Override
public void save(User u)
{
// 读取配置文件
Configuration cfg = new Configuration().configure();;
//创建服务注册对象
ServiceRegistry serviceRegistry =new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
//创建session工厂
SessionFactory sf = cfg.configure().buildSessionFactory(serviceRegistry);
//获取session
Session session = sf.openSession();
Transaction tran = session.beginTransaction();//开启事务
try
{
session.save(u);//插入数据
tran.commit(); //提交
}
catch (HibernateException e)
{
e.printStackTrace();
tran.rollback();//回滚
}
finally
{
session.close();
}
}
}
=============== 测试插入的功能 ===============
package com.my.dao;
import com.my.bean.User;
public class TestDao
{
public static void main(String[] args)
{
User u = new User();
u.setId(1);
u.setUsername("zhangsan");
u.setPassword("123456");
UserDao dao = new UserDaoImpl();
dao.save(u);
}
}
【hibernate的API】
(1)save(Object obj);//插入
(2)get(Class cls, Serializable id);//根据ID查询
(3)delete(Object obj);//删除