用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>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。