用dbutils和hibernate分别实现CRUD操作

=====================用dbutils实现CRUD操作========================

1.bean: Teacher.java

package beans;
public class Teacher {
    String id;
    String tname;
    String tage;
    //setter、getter
    @Override
    public String toString() {
        return "Teacher [id=" + id + ", tname=" + tname + ", tage=" + tage
                + "]";
    }    
}

 

2. 实现操作的类:CRUD.java

package dbs;
import beans.Teacher;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
public class CRUD {
    
    //
    public static int save(Teacher teacher) throws SQLException {
        String sql = "insert into teacher values(null,?,?)";
        int i = DB.getQueryRunner().update(sql, teacher.getTname(),teacher.getTage());
//        System.out.println("save  i="+i);
        return i;
    }
    
    //
    public static int delete(Teacher teacher) throws SQLException {
        String sql = "delete from teacher where id=?;";
        int i = DB.getQueryRunner().update(sql, teacher.getId());
//        System.out.println("delete  i="+i);
        return 1;
    }
    
    //
    public static int update(Teacher teacher) throws SQLException {
        String sql = "update teacher set tname = ?,tage=? where id=?;";
        int i = DB.getQueryRunner().update(sql, teacher.getTname(),teacher.getTage(),teacher.getId());
//        System.out.println("update  i="+i);
        return i;
    }
    
    //查询所有的记录
    public static List<Teacher> getAllTeacher() throws SQLException{
        List <Teacher> list = null;
        String sql = "select * from teacher;";
        list =  DB.getQueryRunner().query(sql,new BeanListHandler<Teacher>(Teacher.class));
        return list;
    }
    
    //根据id查询一条记录
    public static Teacher findById(String id) throws SQLException {
        String sql = "select * from teacher where id="+id;
        Teacher t = DB.getQueryRunner().query(sql, new BeanHandler<Teacher>(Teacher.class));
        return t;
    }
}

3. DB工具类:DB.java

package dbs;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import org.apache.commons.dbutils.QueryRunner;
public class DB {
    public static void main(String[] args) {
        
        DB db = new DB();
        System.out.println(db.getQueryRunner());
    }
    private static DataSource  dataSource = null ; 
    
    //初始化数据源
    static{
    dataSource =   new ComboPooledDataSource("henu");
    }
    
    //获取数据源
     public static DataSource getDatasource() {
        return dataSource;
    } 

     public static synchronized QueryRunner getQueryRunner() {
         return new QueryRunner(DB.getDatasource());
     }
}

 

4.dbutils的配置

在classpath下面放:c3p0-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<c3p0-config>
    <named-config name="henu">
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql:///ckrdb</property>
        
        <property name="acquireIncrement">5</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">10</property>
        <property name="maxPoolSize">50</property>
        
        <property name="maxStatements">20</property>
        <property name="maxStatementsPerConnection">5</property>
    </named-config>
</c3p0-config>

 

=========================用hibernate实现CRUD操作==========================

1. Bean: Person.java

 

package hibernate.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Person implements Serializable{
    private static final long serialVersionUID = 1L;
    private int id;
    private String name;
    private String passwd;
    
    @GeneratedValue
    @Id
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    public String getPasswd() {
        return passwd;
    }
    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", passwd=" + passwd
                + "]";
    }
}

 使用注解;id为自动增长。

 

2. Hibernate的工具类:HibernateUtils.java ,主要实现SessionFactory的获取和关闭

package hibernate.utils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtils {
    
    private static SessionFactory sf;
    
    //获取SessionFactory
    public static SessionFactory beforeClass(){
        
        Configuration configuration = new Configuration().configure();
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties()).build();
        sf = configuration.buildSessionFactory(serviceRegistry);
        return sf;
    }
    
    //关闭SessionFactory
    public static void afterClass(SessionFactory sessionFactory){
        sessionFactory.close();
    }
}

 

 

3. CRUD的实现类(用main方法测试) CRUD.java

package hibernate.utils;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import hibernate.model.Person;
public class CRUD {
    private static SessionFactory sf;
    private static Session session;
    private static Transaction transaction;
    static{
        sf = HibernateUtils.beforeClass();
        session = sf.getCurrentSession();
        transaction =session.beginTransaction();
    }
    
    //添加或更新
    public static void saveOrUpdate(Person person) {
        try {
            session.saveOrUpdate(person);
            transaction.commit();
        } catch (Exception e) {
            transaction.rollback();
            e.printStackTrace();
        }
    }
    
    //删除
    public static void delete(Person person) {
        try {
            session.delete(person);
            transaction.commit();
        } catch (Exception e) {
            transaction.rollback();
            e.printStackTrace();
        }
    }
    
    //获取所有记录
    public static List<Person> findAll() {
        List<Person> list = null;
        try {
            list = session.createQuery("from Person").list();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
    
    //根据id
    public static Person findById(int id) {
        //"from Person where id="+person.getId()
        Person person = null;
        try {
            person = (Person) session.get(Person.class, id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return person;
    }
    
    public static void main(String[] args) {
        Person p = new Person();
        //-------------------test saveOrUpdate-------------------
//        p.setId(2);
//        p.setName("cc");
//        p.setPasswd("fas");
//        CRUD.saveOrUpdate(p);
        
        //-------------------test findById-------------------
//        Person person =  CRUD.findById(2);
//        System.out.println(person);
        
        
        //-------------------test findAll-------------------
//        List<Person> list =  CRUD.findAll();
//        for(Person p2:list) {
//            System.out.println(p2);
//        }
        
        //-------------------test delete-------------------
        p.setId(10);
        CRUD.delete(p);
        
        //关闭工厂
        HibernateUtils.afterClass(sf);
    }
}

 

4. 配置文件: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">
<hibernate-configuration>
    <session-factory>        
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.pool_size">1</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <property name="current_session_context_class">thread</property>
        <!-- 给Person加一个映射 -->
        <mapping class="hibernate.model.Person"/>
    </session-factory>
</hibernate-configuration>

5.日志配置:log4j.properties

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c:%L - %m%n
log4j.rootLogger=warn, stdout
log4j.logger.org.hibernate.tool.hbm2ddl=debug

 

posted @ 2015-01-09 17:03  cymin  阅读(736)  评论(0编辑  收藏  举报