1,新建java项目,导入相关jar包。
2,新建User实体com.bean.user,并创建数据库。
3,在src下创建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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql:///数据库名</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/bean/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
4,创建User.hbm.xml,class name为实体文件名,table为表明,name可以自己随意,colum为数据库中字段名,当name和colum相同时,colum可以省略不写。
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.bean">
<class name="User" table="user">
<id name="id" column="id">
<generator class="increment"/>
</id>
<property name="username" column="username"/>
<property name="password"/>
</class>
</hibernate-mapping>
5,创建hibernate.java测试。
package com.util;
import java.util.Iterator;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.bean.User;
public class hibernateUtil {
public static void main(String[] args) {
Configuration config=new Configuration().configure();
//获取session工厂
SessionFactory factory=config.buildSessionFactory();
//打开session
Session session=factory.openSession();
User user=new User();
//开启事务
Transaction ts=session.beginTransaction();
//增加
// user.setId(4);
// user.setUsername("浪费");
// user.setPassword("888");
// session.save(user);
// 提交
// ts.commit();
//删除
// user.setId(2);
// session.delete(user);
//修改
// user.setId(3);
// user.setUsername("ko");
// user.setPassword("999");
// session.update(user);
//查询某一条
// Query query=session.createQuery("from User u where u.id=:userid");
// query.setInteger("userid", 4);
//查询所有
Query query=session.createQuery("from User");
Iterator<User> i=query.iterate();
while(i.hasNext()){
User useru=i.next();
System.out.println(useru.getId()+"---"+useru.getUsername()+"---"+useru.getPassword());
}
session.close();
factory.close();
}
}
本人初学java,欢迎各位前辈指导!
联系qq709892219