采用myeclipse开发hibernate,新建一个project,是myeclipse下的j2ee project中的web project,在工程中Add Hibernate Capabilities..。对src根目录下的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="connection.username">root</property>
<property name="connection.url">jdbc:mysql://localhost:3306/tibcomonitor</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.password">111111</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="myeclipse.connection.profile">conmysql</property>
<mapping resource="dao/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
在数据库tibcomonitor中存在一个表,建表的语句为:
CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(50) default NULL,
`password` varchar(20) default NULL,
`remark` varchar(100) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
在src中新建一个包,dao,在其下新建一个操作这个表的类User.java
package dao;
public class User {
private int id;
private String username;
private String password;
private String remark;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
在同一个包下(也就是dao中)建立这个表的对应的映射文件
<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-mapping>
<class name="dao.User" table="user">
<id name="id" column="id" type="int">
<generator class="increment"/>
</id>
<property
name="username"
column="username"
type="string"/>
<property
name="password"
column="password"
type="string" />
<property
name="remark"
column="remark"
type="string" />
</class>
</hibernate-mapping>
这个文件的路径要在hibernate.cfg.xml文件中进行声明,hibernate.cfg.xml文件中的<mapping resource="dao/User.hbm.xml" />这句就是这个映射文件的声明。
下面就可以进行测试:
import org.hibernate.cfg.*;
import org.hibernate.*;
import java.util.*;
import dao.User;
public class TestHib {
public static SessionFactory sessionFactory;//数据存储源
static {
try {
Configuration config = new Configuration().configure();
sessionFactory = config.buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 将一个customer对象存入database
* @Customer customer Object
*/
public void saveUser(User ct) {
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.save(ct);
session.flush();
tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public void delete(int id) {
Session session = sessionFactory.openSession();
Transaction tran = session.beginTransaction() ;
String hql = "Delete FROM User Where id=?" ; //删除这时候使用的也是映射的时候的类,并不是数据库中的表名
Query q = session.createQuery(hql) ;
q.setInteger(0, id) ;
q.executeUpdate() ;
tran.commit() ;
}
public void test()
{
User ct = new User();
//ct.setId(5);
ct.setUsername("蔺洋");
ct.setPassword("10007");
ct.setRemark("我爱你中国");
this.saveUser(ct);
this.findAll();
this.loadUpdate(ct.getId(),"phop");
}
/*
* 查找所有的customer object
*/
public void findAll() {
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
List user = session.createQuery(
"from User").list(); //特别要注意的是:这个from后面的因该是对应的数据库表/的那个操作类而不是数据库中的表的名字
Iterator it = user.iterator();
System.out.println("append:"+user.size());
// while()
for(int i=0;i<user.size();i++)
{
// User c = (User)it.next();
User c = (User)user.get(i);
System.out.println("ID:" + c.getId());
System.out.println("Name:" + c.getUsername());
System.out.println("Pass:" + c.getPassword());
}
tx.commit();
} catch (Exception e) {
tx.rollback();
} finally {
session.close();
}
}
/*
* 修改customer Name
* @name
*/
public void loadUpdate(int id, String name) {
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
User c = (User) session.load(User.class, id);
c.setUsername(name);
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestHib a=new TestHib();
a.test();
}
}