使用MyBatis集成阿里巴巴druid鏈接池(不使用spring)

    •  

      在工做中發現mybatis默認的鏈接池POOLED,運行時間長了會報莫名其妙的鏈接失敗錯誤。所以採用阿里巴巴的Druid數據源(碼雲連接 ,中文文檔連接)。 mybatis更多數據源參考博客連接 。html

      1 環境

      eclipse mars2 + maven3.3.9 + mysql5.7java

      2 開發過程

      項目碼雲地址連接mysql

      文件目錄結構以下: 文件結構nginx

      2.0 創建數據表

      在本地mysql數據庫中創建名爲test的database,並創建user表:git

      CREATE DATABASE test default charset=utf8; CREATE TABLE `user` ( `name` varchar(64) DEFAULT NULL, `age` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into `user`(`name`,`age`) values ('葉莜落',27),('張三丰',128); 

      2.1 創建一個maven工程,POM文件以下:

      <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.yeyouluo.mybatis.druid</groupId> <artifactId>mybatis-druid</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <myabtis.version>3.4.1</myabtis.version> </properties> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${myabtis.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.30</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.14</version> </dependency> </dependencies> </project> 

      2.2 配置文件

      ①db.propertiesgithub

      driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test username=root password=root 

      ②mybatis-config.xmlspring

      <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 引用db.properties配置文件 --> <properties resource="db.properties" /> <typeAliases> <typeAlias type="com.yeyouluo.mybatis.druid.utils.DruidDataSourceFactory" alias="DRUID" /> </typeAliases> <!-- development : 開發模式 work : 工做模式 --> <environments default="work"> <environment id="work"> <transactionManager type="JDBC" /> <!-- 配置數據庫鏈接信息 --> <dataSource type="DRUID"> <!-- value屬性值引用db.properties配置文件中配置的值 --> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> <!-- mybatis的mapper文件,每一個xml配置文件對應一個接口 --> <mappers> <mapper resource="mapper/userMapper.xml" /> </mappers> </configuration> 

      ③在resources目錄下創建userMapper.xmlsql

      <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> <mapper namespace="com.yeyouluo.mybatis.druid.dao.userDao"> <select id="findAllUsers" resultType="com.yeyouluo.mybatis.druid.pojo.User"> select * from user </select> </mapper> 

      2.3 實體類 User

      package com.yeyouluo.mybatis.druid.pojo;
      
      public class User { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [name=" + name + ", age=" + age + "]"; } } 

      2.4 工具類

      ①DruidDataSourceFactory.java數據庫

      package com.yeyouluo.mybatis.druid.utils;
      
      import java.sql.SQLException;
      import java.util.Properties;
      import javax.sql.DataSource;
      import org.apache.ibatis.datasource.DataSourceFactory;
      import com.alibaba.druid.pool.DruidDataSource;
      
      public class DruidDataSourceFactory implements DataSourceFactory { private Properties props; @Override public DataSource getDataSource() { DruidDataSource dds = new DruidDataSource(); dds.setDriverClassName(this.props.getProperty("driver")); dds.setUrl(this.props.getProperty("url")); dds.setUsername(this.props.getProperty("username")); dds.setPassword(this.props.getProperty("password")); // 其餘配置能夠根據MyBatis主配置文件進行配置 try { dds.init(); } catch (SQLException e) { e.printStackTrace(); } return dds; } @Override public void setProperties(Properties props) { this.props = props; } } 

      ②MyBatisUtil.javaapache

      package com.yeyouluo.mybatis.druid.utils;
      
      import java.io.InputStream;
      
      import org.apache.ibatis.io.Resources;
      import org.apache.ibatis.session.SqlSession;
      import org.apache.ibatis.session.SqlSessionFactory;
      import org.apache.ibatis.session.SqlSessionFactoryBuilder;
      
      public class MyBatisUtil { private static final String configFile = "mybatis-config.xml"; /** * 建立鏈接 */ public static SqlSession getSession() { SqlSession session = null; try { InputStream is = Resources.getResourceAsStream(configFile); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); session = factory.openSession(); } catch (Exception e) { e.printStackTrace(); } return session; } public static void closeSession(SqlSession session) { session.close(); } public static void main(String[] args) { SqlSession session = MyBatisUtil.getSession(); System.out.println(session); session.close(); } } 

      2.5 DAO

      ①接口IUserDao.java

      package com.yeyouluo.mybatis.druid.dao; import java.util.List; import com.yeyouluo.mybatis.druid.pojo.User; public interface IUserDao { public List<User> findAllUsers(); } 

      ②實現類UserDao.java

      package com.yeyouluo.mybatis.druid.dao.impl;
      
      import java.util.List;
      
      import org.apache.ibatis.session.SqlSession;
      
      import com.yeyouluo.mybatis.druid.dao.IUserDao;
      import com.yeyouluo.mybatis.druid.pojo.User;
      import com.yeyouluo.mybatis.druid.utils.MyBatisUtil;
      
      public class UserDao implements IUserDao { private static final String namespace = "com.yeyouluo.mybatis.druid.dao.userDao."; @Override public List<User> findAllUsers() { List<User> users = null; SqlSession session = MyBatisUtil.getSession(); try { users = session.selectList(namespace + "findAllUsers", User.class); //注意:此處有陷阱,若是作了更新、插入或刪除操做,必須使用: //session.commit(); } catch (Exception e) { e.printStackTrace(); }finally{ MyBatisUtil.closeSession(session); } return users; } } 

      2.6 測試類UserDaoTest.java

      package com.yeyouluo.mybatis.druid.dao.test;
      
      import java.util.List;
      
      import com.yeyouluo.mybatis.druid.dao.IUserDao;
      import com.yeyouluo.mybatis.druid.dao.impl.UserDao;
      import com.yeyouluo.mybatis.druid.pojo.User;
      
      public class UserDaoTest { public static void main(String[] args) { // TODO Auto-generated method stub IUserDao userDao = new UserDao(); List<User> users= userDao.findAllUsers(); for(User user : users){ System.out.println(user.toString()); } } } 

      3 結果

      結果

      4 參考

      Jar程序使用MyBatis集成阿里巴巴druid鏈接池

相關文章
相關標籤/搜索