用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的实现类 CRUD.java

package hibernate.utils;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import hibernate.model.Person;
public class CRUD {
    private static SessionFactory sf;
    //执行一次初始化工厂
    static{
        sf = HibernateUtils.beforeClass();
    }

    //添加
    public static void save(Person person) {
        Session session = sf.getCurrentSession();
        session.beginTransaction();
        session.save(person);
        session.getTransaction().commit();
    }

    //删除
    public static void delete(Person person) {
        Session session = sf.getCurrentSession();
        session.beginTransaction();
        session.delete(person);
        session.getTransaction().commit();
    }

    //修改
    public static void update(Person person) {
        Session session = sf.getCurrentSession();
        session.beginTransaction();
        String sql = "update Person p set p.name=‘"+person.getName()+"‘,p.passwd=‘"+person.getPasswd()+"‘ where p.id="+person.getId();
        Query query = session.createQuery(sql);
        int i = query.executeUpdate();
//        System.out.println(i);
        session.getTransaction().commit();
    }

    //获取所有记录
    public static List<Person> findAll() {
        Session session = sf.getCurrentSession();
        session.beginTransaction();
        Query query = (Query) session.createQuery("from Person");
        List<Person> list = query.list();
        session.getTransaction().commit();
        return list;

    }

    //根据id获取记录
    public static List<Person> findById(Person person) {
        Session session = sf.getCurrentSession();
        session.beginTransaction();
        Query query = (Query) session.createQuery("from Person where id="+person.getId());
        List<Person> list = query.list();
        session.getTransaction().commit();
        return list;
    }
}

4. 测试类: PersonTest.java

package hibernate.model;
import hibernate.utils.CRUD;
import hibernate.utils.HibernateUtils;
import java.util.List;
import org.hibernate.SessionFactory;
import org.junit.Test;
public class PersonTest {
    private static SessionFactory sf;
    //只执行一次初始化工厂
    static{
        sf = HibernateUtils.beforeClass();
    }

    @Test
    public void test() {

        Person p = new Person();
        //-------------------test save-------------------
//        p.setName("vfs");
//        p.setPasswd("vds");
//        CRUD.save(p);

        //-------------------test delete-------------------
//        p.setId(13);
//        CRUD.delete(p);

        //-------------------test update-------------------
//        p.setId(10);
//        p.setName("agdh");
//        p.setPasswd("rww");
//        CRUD.update(p);

        //-------------------test findAll(finfById)-------------------
//        p.setId(10);
//        List<Person> list =  CRUD.findAll();
//        for(Person p2:list) {
//            System.out.println(p2);
//        }
    }

    //只执行一次关闭工厂
    static{
        HibernateUtils.afterClass(sf);
    }
}

5. 配置文件: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>
时间: 2024-10-25 20:04:08

用dbutils和hibernate分别实现CRUD操作的相关文章

Hibernate对象的CRUD操作

1.  Hibernate对象的CRUD操作 1.1.  对象的三种状态 瞬时(Transient) - 由new操作符创建,且尚未与HibernateSession 关联的对象被认定为瞬时(Transient)的.瞬时(Transient)对象不会被持久化到数据库中,也不会被赋予持久化标识(identifier).如果瞬时(Transient)对象在程序中没有被引用,它会被垃圾回收器(garbage collector)销毁.使用Hibernate Session可以将其变为持久(Persis

Spring+Jersey+JPA+Hibernate+MySQL实现CRUD操作案例

本文承接我的另一篇博文:Spring+Jersey+Hibernate+MySQL+HTML实现用户信息增删改查案例(附Jersey单元测试),主要更改内容如下: Spring配置文件applicationContext中原先使用的是Hibernate,现在改为Hibernate对JPA的支持: 增加了C3P0连接池: 修改了Dao操作实现,改为Spring接管的JPA实现. 如果读者想详细查看Spring整合Jersey与前端交互可以点击上述连接.本文主要介绍以上三处修改内容,并且使用Jers

hibernate入门(1) - CRUD操作

第一步:hibernate的配置文件 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

Hibernate中的CRUD操作

1.添加数据操作 插入数据使用session对象的save()方法完成.   插入代码: @Test public void Test1(){ SessionFactory sessionFactory = HibernateUtils.getFactory(); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); UserEntity user = new Us

Spring MVC + Hibernate + Maven: Crud操作示例

Alexey是一个在使用Java,TestNG 和Selenium的自动化WEB应用程序中有丰富经验的测试开发者.他如此的喜欢QA以至于在下班后他为初级QA工程师提供培训课程. 在这篇文章中我想介绍一个Spring MVC + Hibernate + Maven例子.这组技术主要涉及一些基础知识,我想在每一个必要的地方详细解释它.本篇话题范围以外的更多资源,我会提供链接方便你阅读.在文章的最后,我将发布一个GitHub的链接. 目标 示例web应用程序是基于Spring MVC, Hiberna

hibernate的CRUD操作

本文简单总结一下hibernate的具有映射关系CRUD操作,主要使用到了cascade和fetch,其中cascade针对的是CUD操作,表示级联关系,fetch针对的是R操作,表示级联加载方式. 1.先看下javaEE的API中关于cascade的描述 javax.persistence Enum CascadeType java.lang.Object java.lang.Enum<CascadeType> javax.persistence.CascadeType All Implem

Hibernate系列(五):利用Hibernate完成简单的CRUD操作

这里利用Hibernate操作数据库完成简单的CRUD操作. 首先,我们需要先写一个javabean: package cn.itcast.domain; import java.util.Date; public class User { private int id; private String name; private Date birthday; public int getId() { return id; } public void setId(int id) { this.id

【SSH三大框架】Hibernate基础第五篇:利用Hibernate完成简单的CRUD操作

这里利用Hibernate操作数据库完成简单的CRUD操作. 首先,我们需要先写一个javabean: package cn.itcast.domain; import java.util.Date; public class User { private int id; private String name; private Date birthday; public int getId() { return id; } public void setId(int id) { this.id

【SSH三大框架】Hibernate基础第五篇:利用Hibernate完毕简单的CRUD操作

这里利用Hibernate操作数据库完毕简单的CRUD操作. 首先.我们须要先写一个javabean: package cn.itcast.domain; import java.util.Date; public class User { private int id; private String name; private Date birthday; public int getId() { return id; } public void setId(int id) { this.id