mybatis的整合之路
一、导包
<!--mysql驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
二、步骤:
-
加载驱动
-
用户信息username,password和url
-
-
通过连接获取执行sql的对象,执行sql,处理结果
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbcstudy?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=true";
String username ="root";
String password ="123456";
Connection connection = DriverManager.getConnection(url,username,password);
Statement statement= connection.createStatement(); -
释放连接
三、编写配置文件,提取工具类
-
将数据库连接的信息写到配置文件db.properties中
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=true
username=root
password=123456 -
提取工具类JdbcUtils
static{
Properties p = new Properties();
try {
properties.load(JdbcUtils.class.getClassLoader()
.getResourceAsStream("db.properties"));
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException( "读取db.properties失败",e);
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("找不到这个驱动类",e);
}
}
public static Connection getConnection()throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public static void close(Connection conn) {
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("关闭连接失败",e);
}
}
}
四、增加连接池
1.DBCP
-
导包
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-pool/commons-pool -->
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency> -
编写配置文件
#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=true
username=root
password=123456
#!-- 初始化连接 --
initialSize=10
#最大连接数量
maxActive=50
#!-- 最大空闲连接 --
maxIdle=20
#!-- 最小空闲连接 --
minIdle=5
#!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 --
maxWait=60000
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:【属性名=property;】
#注意:user 与 password 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=UTF8
#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true
#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=
#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED -
重构工具类
static DataSource dataSource = null;
static{
Properties properties = new Properties();
try {
properties.load(JdbcUtils.class.getClassLoader()
.getResourceAsStream("db.properties"));
dataSource = BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("读取db.properties失败",e);
}
}
/**
* 由连接池创建的连接,其实现类由连接池提供.
*/
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
/**
* 连接池提供的实现类,其close方法内部逻辑是,
* 将连接归还给连接池,即它会清空连接对象中的数据,
* 并且将连接标记为空闲态.
*/
public static void close(Connection conn) {
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException( "归还连接失败", e);
}
}
}
2.C3P0
-
导包
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mchange/mchange-commons-java -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>mchange-commons-java</artifactId>
<version>0.2.19</version>
</dependency> -
编写配置文件
-
重构工具类
static DataSource dataSource = null;
static{
try{//xml不用读取,会自动匹配
//创建数据源 工厂模式创建
dataSource = new ComboPooledDataSource("MySQL");//配置文件写法
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 由连接池创建的连接,其实现类由连接池提供.
*/
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
/**
* 连接池提供的实现类,其close方法内部逻辑是,
* 将连接归还给连接池,即它会清空连接对象中的数据,
* 并且将连接标记为空闲态.
*/
public static void close(Connection conn) {
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException( "归还连接失败", e);
}
}
}小结:无论使用什么数据源,本质都是一样的,DataSource接口不变,方法不变。
Mybatis
一、导包
<!--导入依赖-->
<dependencies>
<!--mysqlq驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
</dependencies>
<!--Maven静态资源过滤-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
二、步骤
-
通过SqlSessionFactoryBuilder获取SqlSessionFactory
-
通过SqlSessionFactory 获取SqlSession
-
通过SqlSession获取Mapper实现类
//使用Mybatis第一步 :获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactoryBuilder bulider = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = builder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class); -
通过Mapper实现类就可以进行增删改查操作。
三、重构步骤
-
编写mybatis核心配置文件mybatis-config.xml
-
编写工具类MybatisUtis
//sqlSessionFactory --> sqlSession
public class MybatisUtils {
static SqlSessionFactory sqlSessionFactory = null;
static {
try {
//使用Mybatis第一步 :获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例.
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
} -
编写接口UserMapper,UserMapper.xml
public interface UserMapper {
public List<User> getUserList();
} -
将Mapper添加到mybatis-config.xml中
<mappers>
<mapper class="com.kuang.dao.UserMapper"/>
</mappers>注意点:
-
接口和他的Mapper配置文件必须同名
-
接口和他的Mapper配置文件必须在同一个包下
-
-
测试
Spring
Spring整合Mybatis 三种方式:
-
SqlSessionTemplate(不常用,了解即可)
-
SqlSessionDaoSupport(也不常用,了解)
-
扫描包(重点)
一、导包
<!--导入依赖-->
<dependencies>
<!--mysqlq驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>mchange-commons-java</artifactId>
<version>0.2.19</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<!--spring整合mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<!--Servlet - JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>