Spring的jdbcTemplate 与原始jdbc 整合c3p0的DBUtils 及Hibernate 对比

以User为操作对象

package com.swift.jdbc;

public class User {

    private Long user_id;
    private String    user_code;
    private String    user_name;
    private String    user_password;
    private String    user_state;

    public User() {
        super();
        // TODO Auto-generated constructor stub
    }
    public User(Long user_id, String user_code, String user_name, String user_password, String user_state) {
        super();
        this.user_id = user_id;
        this.user_code = user_code;
        this.user_name = user_name;
        this.user_password = user_password;
        this.user_state = user_state;
    }
    public Long getUser_id() {
        return user_id;
    }
    public void setUser_id(Long user_id) {
        this.user_id = user_id;
    }
    public String getUser_code() {
        return user_code;
    }
    public void setUser_code(String user_code) {
        this.user_code = user_code;
    }
    public String getUser_name() {
        return user_name;
    }
    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }
    public String getUser_password() {
        return user_password;
    }
    public void setUser_password(String user_password) {
        this.user_password = user_password;
    }
    public String getUser_state() {
        return user_state;
    }
    public void setUser_state(String user_state) {
        this.user_state = user_state;
    }
    @Override
    public String toString() {
        return "User [user_id=" + user_id + ", user_code=" + user_code + ", user_name=" + user_name + ", user_password="
                + user_password + ", user_state=" + user_state + "]";
    }

}

原始JDBC

这个注意ResultSet 是一个带指针的结果集,指针开始指向第一个元素的前一个(首元素),不同于iterator 有hasNext() 和next() ,他只有next()

package com.swift.jdbc;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DemoJDBC {

    public static void main(String[] args) throws ClassNotFoundException, SQLException, PropertyVetoException {

        findAll();
        User user=findById(9l);
        System.out.println(user);
        user.setUser_name("HanMeimei");
        update(user);
    }

    private static void update(User user) throws PropertyVetoException, SQLException {

        ComboPooledDataSource dataSource=new ComboPooledDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/crm");
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setPassword("root");
        dataSource.setUser("root");
        dataSource.setMinPoolSize(5);
        dataSource.setMaxIdleTime(2000);
        Connection con= dataSource.getConnection();
        String sql="update sys_user set user_name=‘"+user.getUser_name()+"‘ where user_id="+user.getUser_id();
        PreparedStatement statement = con.prepareStatement(sql);
        statement.executeUpdate();
        System.out.println("ok");

    }

    private static User findById(long id) throws ClassNotFoundException, SQLException {

        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/crm","root","root");
        Statement statement = con.createStatement();
        ResultSet rs = statement.executeQuery("select * from sys_user where user_id="+id);
        User user=null;
        while(rs.next()) {
            user=new User(rs.getLong("user_id"),rs.getString("user_code"),
                    rs.getString("user_name"),rs.getString("user_password"),
                    rs.getString("user_state"));
        }
        return user;

    }

    private static void findAll() throws ClassNotFoundException, SQLException {

        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/crm?user=root&password=root");
        PreparedStatement statement = connection.prepareStatement("select * from sys_user");
        ResultSet rs = statement.executeQuery();
        List<User> list=new ArrayList<>();
        while(rs.next()) {
            Long id = rs.getLong("user_id");
            String code=rs.getString("user_code");
            String name=rs.getString("user_name");
            String password=rs.getString("user_password");
            String state=rs.getString("user_state");
            User user=new User();
            user.setUser_code(code);
            user.setUser_id(id);
            user.setUser_password(password);
            user.setUser_name(name);
            user.setUser_state(state);
            list.add(user);
        }
        for(User u:list) {
            System.out.println(u);
        }
        rs.close();
        connection.close();
    }

}

整合c3p0的DBUtils

c3p0整合了连接数据库的Connection ,提供更快速的连接

package com.swift.c3p0;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3P0Utils {

    private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
    private static ThreadLocal<Connection> thread=new ThreadLocal<>();
//    static {
//        try {
//            dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/crm");
//            dataSource.setDriverClass("com.mysql.jdbc.Driver");
//            dataSource.setUser("root");
//            dataSource.setPassword("root");
//            dataSource.setMinPoolSize(5);
//        } catch (PropertyVetoException e) {
//            e.printStackTrace();
//        }
//    }

    public static DataSource getDataSource() {
        return dataSource;
    }

    public static Connection getConnection() {
        Connection con = thread.get();
        if(con==null) {
            try {
                con = dataSource.getConnection();
                thread.set(con);
                con=thread.get();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return con;

    }
    public static void main(String[] args) {
        Connection con = C3P0Utils.getConnection();
        System.out.println(con);
    }
}

并可以直接加载xml配置文件,强于(DBCP连接池,他只支持properties文件)

<c3p0-config>
    <default-config>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/crm</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="user">root</property>
        <property name="password">root</property>
    </default-config>
</c3p0-config>

DBUtils的杀手锏QueryRunner

可以使用?了,放置恶意注意,也提供自动增加‘ ‘符号,这个要注意

package com.swift.dbutils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.swift.c3p0.C3P0Utils;
import com.swift.jdbc.User;

public class DemoQueryRunner {

    private static QueryRunner qr=new QueryRunner(C3P0Utils.getDataSource());
    static List<User> users=new ArrayList<User>();

    public static void main(String[] args) throws SQLException {
        //查找所有
        users=findAll();
        for(User user:users) {

            System.out.println(user);
        }
        //通过Id查找
        User user=findById(9l);
        System.out.println(user);
        //更新
        user.setUser_name("韩梅梅");
        System.out.println("===================================");
        System.out.println(user);
        update(user);

    }

    private static void update(User user) throws SQLException {

        int update = qr.update(
                "update sys_user set user_name=? where user_id=?",user.getUser_name(),user.getUser_id());
        System.out.println(user.getUser_name()+update);

    }

    private static List<User> findAll() throws SQLException {
        List<User> users = qr.query("select * from sys_user ", new BeanListHandler<User>(User.class));
        return users;
    }

    private static User findById(long l) throws SQLException {

        User user = qr.query(
                "select * from sys_user where user_id=?",new BeanHandler<User>(User.class),l);
        return user;

    }

}

Hibernate 有个核心配置文件

<?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-core-5.0.7.Final.jar的org.hibernate包下的hibernate-configuration-3.0.dtd文件中找 -->
<hibernate-configuration>
    <session-factory>
    <!-- 配置方法:资料\hibernate-release-5.0.7.Final\project\etc\hibernate.properties -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/crm</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>

        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
        <property name="hibernate.c3p0.max_size">10</property>
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.timeout">5000</property>

        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>

        <property name="hibernate.connection.isolation">2</property>

        <!-- 获得当前session放在当前线程中 -->
        <!-- <property name="hibernate.current_session_context_class">thread</property> -->

        <mapping resource="com/swift/hibernate/User.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>这个是使用Hibernate自带的c3p0功能,不需要自己写c3p0.xml文件,但除了需要c3p0的jar包,还需要Hibernate自带的jar包,可以在hibernate包的lib->optional->c3p0中找到,此文件夹中这两个jar:c3p0-0.9.1.jar和hibernate-c3p0-4.2.1.Final.jar都要用,否则异常Could not instantiate connection provider [org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider]

还有个实体类的映射文件

<?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-core-5.0.7.Final.jar的org.hibernate包下的hibernate-mapping-3.0.dtd文件中找 -->
<hibernate-mapping>
    <class name="com.swift.hibernate.User" table="sys_user">
        <id name="user_id" column="user_id">
            <generator class="native"></generator>
        </id>
        <property name="user_code" column="user_code"></property>
        <property name="user_name" column="user_name"></property>
        <property name="user_password" column="user_password"></property>
        <property name="user_state" column="user_state"></property>
    </class>
</hibernate-mapping>

连接数据库是通过session

package com.swift.hibernate;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class DemoHibernate {

    static List<User> users=new ArrayList<User>();
    public static void main(String[] args) {

        users=findAll();
        for(User user:users) {

            System.out.println(user);
        }
    }
    private static List<User> findAll() {

        //new Configuration()是创建Configuration类对象,调用里面的configure方法,读取配置信息,方法返回的又是Configuration类型
        Configuration config=new Configuration().configure();
        SessionFactory sf = config.buildSessionFactory();
        Session session = sf.openSession();
        Query query = session.createQuery("from User");
        users= query.list();
        session.close();
        return users;
    }

}

原文地址:https://www.cnblogs.com/qingyundian/p/9094572.html

时间: 2024-10-08 08:58:51

Spring的jdbcTemplate 与原始jdbc 整合c3p0的DBUtils 及Hibernate 对比的相关文章

JDBC整合c3p0数据库连接池 解决Too many connections错误

前段时间,接手一个项目使用的是原始的jdbc作为数据库的访问,发布到服务器上在运行了一段时间之后总是会出现无法访问的情况,登录到服务器,查看tomcat日志发现总是报如下的错误. Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection, message from server: "Too man

SPRING IN ACTION 第4版笔记-第十章Hitting the database with spring and jdbc-001-Spring对原始JDBC的封装

1.spring扩展的jdbc异常 2.Template的运行机制 Spring separates the fixed and variable parts of the data-access process into two distinct classes: templates and callbacks. Templates manage the fixed part of the process,whereas your custom data-access code is hand

使用Spring的jdbcTemplate进一步简化JDBC操作

先看applicationContext.xml配置文件: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="

Hibernate整合C3P0实现连接池&lt;转&gt;

Hibernate整合C3P0实现连接池 Hibernate中可以使用默认的连接池,无论功能与性能都不如C3PO(网友反映,我没有测试过),C3P0是一个开源的JDBC连接池,它实 现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展.目前使用它的开源项目有Hibernate,Spring等. C3P0是一个易于使用JDBC3规范和JDBC2可选的扩展定义的功能增强,使传统的JDBC驱动程序“enterprise-ready”库. 特别是C3P0提供了一些有用的服务:适应传统的基于

spring与jdbc整合详解

先上一段简单示例 public class MyTemplate { private DataSource dataSource; public DataSource getDataSource() { return dataSource; } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public void insert(String sql) throws SQLExc

Spring与JDBC整合应用

Spring与JDBC整合背景: 1.Spring提供了编写Dao的工具类:JdbcTemplate JdbcTemplate.update("insert....",参数); JdbcTemplate.query();//查询多行记录 JdbcTemplate.queryForObject();//查询单行记录 int rows=JdbcTemplate.queryForInt(); 2.Spring提供了AOP式事务管理(不需要在方法中追加事务提交和回滚) 3.提供了统一的异常处理

【SpringMVC学习04】Spring、MyBatis和SpringMVC的整合

前两篇springmvc的文章中都没有和mybatis整合,都是使用静态数据来模拟的,但是springmvc开发不可能不整合mybatis,另外mybatis和spring的整合我之前学习mybatis的时候有写过一篇,但是仅仅是整合mybatis和spring,所以这篇文章我系统的总结一下spring.mybatis和springmvc三个框架的整合(后面学习到maven时,我会再写一篇使用maven整合的文章,这篇没有用到maven). 1. jar包管理 我之前有写过一篇spring.hi

spring学习(四)spring的jdbcTemplate(增删改查封装)

Spring的jdbcTemplate操作 1.Spring框架一站式框架 (1)针对javaee三层,每一层都有解决技术 (2)到dao 层,使用 jdbcTemplate 2.Spring对不同的持久化都进行了封装 (1)jdbcTemplate  对  jdbc 进行封装 3.jdbcTemplate 使用和 dbutils 使用很相似,都是对数据库进行 crud 操作 4.使用jdbcTemplate 实现增删改查操作 增加: 1.导入 jdbcTemplate 相关jar 包 一定要导

Spring之JDBCTemplate学习

一.Spring对不同的持久化支持: Spring为各种支持的持久化技术,都提供了简单操作的模板和回调 ORM持久化技术 模板类 JDBC org.springframework.jdbc.core.JdbcTemplate Hibernate5.0 org.springframework.orm.hibernate5.HibernateTemplate IBatis(MyBatis) org.springframework.orm.ibatis.SqlMapClientTemplate JPA