hibernate的初体验

 
 hibernate初级入门,实现增删改查
1. 添加数据库表user
CREATE TABLE user (
   id  int(11) NOT NULL AUTO_INCREMENT ,
   username  varchar(50)  DEFAULT NULL ,
   age  int(11) DEFAULT NULL ,
   PRIMARY KEY (id)
);
2.创建pojo类User.java
 
package com.bobo.domain;
import java.io.Serializable;
//domain对象/JavaBean/pojo (plain old/ordinary java object)简单java对象
//hibernate需要序列化对象 这样可以唯一的对应数据库的一条记录
public class User implements Serializable{
 private static final long serialVersionUID = 1L;
 private Integer id;
 private String userName;
 private Integer age;
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public Integer getAge() {
  return age;
 }
 public void setAge(Integer age) {
  this.age = age;
 }
}
3.配置user表和对象User的关系映射配置,配置文件: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">
<hibernate-mapping >
        <class name="com.bobo.domain.User">
         <id name="id" column="id" type="java.lang.Integer">
             <!--主键生成策略-->
             <generator class="increment"></generator>
        </id>
       <property name="userName" column="username" type="java.lang.String"/>
       <property name="age" column="age" type="java.lang.Integer"/>
</class>
</hibernate-mapping>
 
4.配置hibernate的核心文件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.MySQLDialect</property>
      <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="connection.url">jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf-8</property>
      <property name="connection.username">root</property>
      <property name="connection.password">root</property>
  
      <property name="show_sql">true</property>
      <!--加载类与数据库表映射配置-->
      <mapping resource="com/bobo/domain/User.hbm.xml"/>
 </session-factory> 
</hibernate-configuration>       
5.初始化配置文件的工具类
package com.bobo.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
 * 初始化配置工具类,获取MySessionFactory对象,确保只有一个,因为它很好资源 
 *
 */
final public class MySessionFactory {
    private static SessionFactory sessionFactory = null;
    private MySessionFactory(){
    }
    static{
      sessionFactory = new Configuration().configure().buildSessionFactory();
    }   
    public static SessionFactory getSessionFactory(){
        return sessionFactory;
    }
}
 6.写测试类TestMain.java
package com.bobo.view;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.*;
import com.bobo.domain.User;
import com.bobo.util.MySessionFactory;
public class TestMain {
 public static void main(String[] args) {
  //添加用户
  //addUser();
  //更新用户
  updateUser();
  
 }
 //删除用户
 public static void deleteUser() {
     Session session = MySessionFactory.getSessionFactory().openSession();
     Transaction tx = session.beginTransaction();
     User user = (User)session.load(User.class, 3);
     session.delete(user); //删除操作 delete from User where id=?
     tx.commit();
     session.close();
 }
 //更新用户
 public static void updateUser() {
     SessionFactory sessionFactory = MySessionFactory.getSessionFactory();
    Session session = sessionFactory.openSession();
    Transaction tx = null;
    try{
         tx = session.beginTransaction();
         User user = (User) session.load(User.class, 3);//执行select 操作select user0_.id as id1_0_0_, user0_.username as username2_0_0_, user0_.age as age3_0_0_ from User user0_ where user0_.id=?
         user.setAge(19);//执行了update操作 update User set username=?, age=? where id=?
         tx.commit();
  }catch(Exception e){
        if(tx != null) tx.rollback();
        throw new RuntimeException(e.getMessage());
  }finally{
     if(session != null && session.isOpen())
      session.close();
  }
 }
 //添加用户
 public static void addUser() {
      //1.初始化hibernate配置
      Configuration cfg = new Configuration().configure();
     //2.创建一个SessionFactory
     SessionFactory sessionFactory = cfg.buildSessionFactory();
     //3.获取一个session对象
     Session session = sessionFactory.openSession();
     //4.开启事务
     Transaction tx = session.beginTransaction();
     //5.插入操作
     User user = new User();
     user.setUserName("bobo");
     user.setAge(20);
     session.save(user);
     //6.提交事务
     tx.commit();
     //7.关闭资源
    session.close();
  }
}
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值