要使用hibernate首先要有jar包,将其添加到项目中。
1,新建一个hibernate.cfg.xml文件,用于映射数据库,将数据库中的信息对象化。
<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="myeclipse.connection.profile">
JDBC for MySQL
</property>
连接MYSQL数据库
<property name="connection.url">
jdbc:mysql://localhost:3306/demo
</property>
数据库的用户名和密码
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">
org.gjt.mm.mysql.Driver
</property>
数据库方言
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
映射XML(User表和User类)
<mapping resource="com/demo/hibernate/beans/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
2,创建User.hbm.xml文件将数据库对象化(类的属性和数据库表的表,字段对应)
<?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 package="com.demo.hibernate.beans">
user表对应User实例
<class name="User" table="user">
主键为id
<id name="id" column="ID" type="integer"></id>
username,password,email字段
<property name="username" column="username" type="string"></property>
<property name="password" column="password" type="string"></property>
<property name="email" column="email" type="string"></property>
</class>
</hibernate-mapping>
3,创建User.java文件(持久化类,实例需要被Hibernate持久化到数据库类中)
private java.lang.Integer id;
public java.lang.Integer getId() {
return id;
}
public void setId(java.lang.Integer id) {
this.id = id;
}
。。。。。。。。等等
创建数据库访问HIbernateSessionFactory
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory=cfg.buildSessionFactory();
session=sessionFactory.openSession();
4,编写数据访问层接口UserDAO,进行数据库操作(要记)
public User getUser(String username) throws HibernateException{
Session session=null;
Transaction tx=null;
User user=null;
try{
//session=HibernateSessionFactory.currentSession()创建session
session=HibernateSessionFactory.currentSession();
//tx=session.beginTransaction()开始事务
tx=session.beiginTransaction();
//Query query=session.createQuery(from User where username=?)创建查询语句
Query query=session.createQuery(from User where username=?);
//query.setString(0,username.trim)给参数赋值
query.setString(0,username.trim);
//user=(User)query.uniquerResult()返回是实例为null或者一个
user=(User)query.uinqueResult();
query=null;
//提交事务
tx.commit();
5,创建UserService.java
面向用户服务,服务层
UserDAO test=UserDAO();
User user=test.getUser("admin");
if(user.getPassword().equeal(password))
{
return true;
}
}
}