使用MyBatis集成阿里巴巴druid连接池(不使用spring)
-
-
在工作中发现mybatis默认的连接池POOLED,运行时间长了会报莫名其妙的连接失败错误。因此采用阿里巴巴的Druid数据源(码云链接 ,中文文档链接)。 mybatis更多数据源参考博客链接 。
1 环境
eclipse mars2 + maven3.3.9 + mysql5.7
2 开发过程
文件目录结构如下:
2.0 建立数据表
在本地mysql数据库中建立名为test的database,并建立user表:
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.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test username=root password=root
②mybatis-config.xml
<?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.xml
<?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.java
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 参考
-