Mybatis学习之路 第一篇
该系列教程只能帮你怎么用,并不涉及源码以及讲解。 本文涉及以下内容: 1. JDBC存在的问题极其代码操作 2. 基于xml的Mybatis的入门程序案例 3. 基于注解的Mybatis的入门程序
JDBC的操作非常繁琐,有很多的操作是我们开发者不需要去关注的,我们的重点应该只是SQL语句的本身。 使用 preparedStatement 向占有位符号传参数存在硬编码,因为 sql 语句的 where 条件不一定,可能多也可能少,修改 sql 还要修改代码,系统不易维护。 对结果集解析存在硬编码(查询列名),sql 变化导致解析代码变化,系统不易维护,如果能将数据库记录封装成 pojo 对象解析比较方便。
JDBC的操作如下:
public static void main ( String[ ] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
Class. forName ( "com.mysql.jdbc.Driver" ) ;
connection = DriverManager. getConnection ( "jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" , "root" , "root" ) ;
String sql = "select * from user where username = ?" ;
preparedStatement = connection. prepareStatement ( sql) ;
preparedStatement. setString ( 1 , "王五" ) ;
resultSet = preparedStatement. executeQuery ( ) ;
while ( resultSet. next ( ) ) {
System. out. println ( resultSet. getString ( "id" ) + " " + resultSet. getString ( "username" ) ) ;
}
} catch ( Exception e) {
e. printStackTrace ( ) ;
} finally {
if ( resultSet!= null) {
try {
resultSet. close ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
if ( preparedStatement!= null) {
try {
preparedStatement. close ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
if ( connection!= null) {
try {
connection. close ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
}
}
PreparedStatement可以防止sql注入问题,Statement不行 PreparedStatement对象的执行方法有三种:
execute:它能执行CRUD中的任意一种语句。它的返回值是bool类型,表示是否有结果集。true为有。 executeUpdate:它只能执行CUD语句,查询语句无法执行。它的返回值是影响数据库记录的行数。 executeQuery:他只能执行SELECT语句,无法执行增删改。执行结果封装的结果集ResultSet对象。
2.1 我们先看一下Mybitis的目录结构:
2.2 导入user表到Mysql数据库中
CREATE TABLE `user` (
`id` int ( 11 ) NOT NULL auto_increment,
`username` varchar ( 32 ) NOT NULL COMMENT '用户名称' ,
`birthday` datetime default NULL COMMENT '生日' ,
`sex` char ( 1 ) default NULL COMMENT '性别' ,
`address` varchar ( 256 ) default NULL COMMENT '地址' ,
PRIMARY KEY ( `id`)
) ENGINE= InnoDB DEFAULT CHARSET= utf8;
insert into `user`( `id`, `username`, `birthday`, `sex`, `address`) values ( 41 , '老王' , '2018-02-27 17:47:08' , '男' , '北京' ) , ( 42 , '小二王' , '2018-03-04 11:34:34' , '女' , '北京' ) , ( 43 , '老王' , '2018-03-07 17:37:26' , '男' , '北京' ) ;
2.3 在pom.xml中添加如下包:
< dependencies>
< dependency>
< groupId> org.mybatis</ groupId>
< artifactId> mybatis</ artifactId>
< version> 3.4.5</ version>
</ dependency>
< dependency>
< groupId> mysql</ groupId>
< artifactId> mysql-connector-java</ artifactId>
< version> 5.1.6</ version>
</ dependency>
< dependency>
< groupId> log4j</ groupId>
< artifactId> log4j</ artifactId>
< version> 1.2.12</ version>
</ dependency>
< dependency>
< groupId> junit</ groupId>
< artifactId> junit</ artifactId>
< version> 4.10</ version>
</ dependency>
</ dependencies>
2.4 编写User的实体类:
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
}
2.5 编写持久层接口 IUserDao
public interface IUserDao {
List< User> findAll ( ) ;
}
2.6 编写持久层接口的映射文件IUserDao.xml
创建位置:必须和持久层接口在相同的包中 名称:必须以持久层接口名称命名文件夹,扩展名是.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
< mapper namespace = " fang.dao.IUserDao" >
< select id = " findAll" resultType = " fang.domain.User" >
select * from user
</ select>
</ mapper>
2.7 编写 SqlMapConfig.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>
< environments default = " mysql" >
< environment id = " mysql" >
< transactionManager type = " JDBC" > </ transactionManager>
< dataSource type = " POOLED" >
< property name = " driver" value = " com.mysql.jdbc.Driver" />
< property name = " url" value = " jdbc:mysql://localhost:3306/eesy_mybatis" />
< property name = " username" value = " root" />
< property name = " password" value = " root" />
</ dataSource>
</ environment>
</ environments>
< mappers>
< package name = " fang.dao" />
</ mappers>
</ configuration>
2.8 将log4j.properties文件粘贴到工程中
log4j. rootCategory= debug, CONSOLE, LOGFILE
log4j. logger. org. apache. axis. enterprise= FATAL, CONSOLE
log4j. appender. CONSOLE= org. apache. log4j. ConsoleAppender
log4j. appender. CONSOLE. layout= org. apache. log4j. PatternLayout
log4j. appender. CONSOLE. layout. ConversionPattern= % d{ ISO8601} % - 6r [ % 15. 15t] % - 5p % 30. 30c % x - % m\n
log4j. appender. LOGFILE= org. apache. log4j. FileAppender
log4j. appender. LOGFILE. File= d: \axis. log
log4j. appender. LOGFILE. Append= true
log4j. appender. LOGFILE. layout= org. apache. log4j. PatternLayout
log4j. appender. LOGFILE. layout. ConversionPattern= % d{ ISO8601} % - 6r [ % 15. 15t] % - 5p % 30. 30c % x - % m\n
2.9 编写测试类
public class MybatisTest {
public static void main ( String[ ] args) throws Exception {
InputStream in = Resources. getResourceAsStream ( "SqlMapConfig.xml" ) ;
SqlSessionFactory factory = new SqlSessionFactoryBuilder ( ) . build ( in) ;
SqlSession sqlSession = factory. openSession ( ) ;
IUserDao userDao = sqlSession. getMapper ( IUserDao. class ) ;
List< User> users = userDao. findAll ( ) ;
for ( User user: users) {
System. out. println ( user) ;
}
sqlSession. close ( ) ;
in. close ( ) ;
}
}
好啦,基于xml的入门程序就结束了。 回顾一下我们基于xml入门案例的创建过程:
在pom.xml中添加需要的4个包 编写User的实体类 编写持久层接口 IUserDao 编写持久层接口的映射文件IUserDao.xml 编写 SqlMapConfig.xml 配置文件 编写测试类
3.1 直接删除配置文件IUserDao.xml
3.2 修改IUserDao中的代码如下:
*加入注解@Select(“select * from user”)
public interface IUserDao {
@Select ( "select * from user" )
List< User> findAll ( ) ;
}
3.3 修改SqlMapConfig.xml配置文件
删除mapper中的resource属性添加class属性
< mappers>
< mapper class = " fang.dao.IUserDao" />
</ mappers>
3.4 直接运行之前编写好的测试类就可以啦
注解相对于xml可以省事不少呢,但是都有优缺点,后续开发大多是xml和注解结合起来的