1.Mybatis的快速入门
1.1 MyBatis开发步骤
MyBatis官网地址:http://www.mybatis.org/mybatis-3/
MyBatis开发步骤:
项目架构:
- 添加MyBatis的坐标
- 创建user数据表
- 编写User实体类 (domain.User)
- 编写UserMapper接口 (mapper.UserMapper)
- 编写Mybatis工具类(utils.MybatisUtil)
- 编写映射文件UserMapper.xml
- 编写核心文件SqlMapConfig.xml
- 编写测试类
1.2 环境搭建
1)导入MyBatis的坐标和其他相关坐标
<!--mybatis坐标-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--mysql驱动坐标-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
<scope>runtime</scope>
</dependency>
<!--单元测试坐标-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--日志坐标-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
- 创建user数据表 ```sql create database mybatis; use mybatis;
create table user( id int(20) auto_increment not null, name varchar(30) default null, pwd varchar(30) default null, primary key (id) )engine = InnoDB default charset = utf8;
drop table user2;
insert into user (id, name, pwd) VALUES (1,’youxi’,’123456’); insert into user (name, pwd) VALUES (‘youxi2’,’123456’);
3. User实体
```java
public class User {
private int id;
private String username;
private String password;
//省略get和set方法
}
- UserMapper( 面向接口编程,方便后续调用session.getMapper(UserMapper.class) )
public interface UserMapper {
// 查询所有
List<User> findAll();
// 根据ID查询
User findById(int id);
// 插入User
int addUser(User user);
// 根据ID删除
int delUserById(int id);
// 修改
int updateUser(User user);
// 模糊查询
List<User> getUserLike(String value);
// 使用map参数
int addUser2(Map<String,Object> map);
}
- UserMapper映射文件(UserMapper.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">
<!-- 这个namespave命名空间指向的是创建的那个UserMapper接口 -->
<mapper namespace="mapper.UserMapper">
<!-- 查询所有 -->
<select id="findAll" resultType="pojo.User">
select * from user;
</select>
<!-- 根据id查询 -->
<select id="findById" parameterType="int" resultType="pojo.User">
select * from user where id = #{id};
</select>
<!-- 插入 -->
<insert id="addUser" parameterType="pojo.User">
insert into user (id, name, pwd) values (#{id}, #{name}, #{pwd});
</insert>
<!-- 删除 -->
<delete id="delUserById" parameterType="int">
delete from user where id=#{id};
</delete>
<!-- 修改 -->
<update id="updateUser" parameterType="pojo.User">
update user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
<!-- 模糊查询 -->
<select id="getUserLike" resultType="User">
select * from user where name like #{value};
</select>
<!-- 使用ResultMap结果集映射 -->
<resultMap id="UserMap" type="User">
<!-- column数据库中的字段,property实体类中的属性 -->
<!-- User.java这个实体类中是password名属性 -->
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserById" resultMap="UserMap">
select * from user where id=#{id};
</select>
<!-- 使用map参数,优点:使用map你需要什么参数就put什么参数,不需要像实体类那样new一个需要写出去全部属性-->
<insert id="addUser2" parameterType="map">
insert into user (id, pwd) values (#{userId}, #{passWord});
</insert>
</mapper>
编写MyBatis核心文件(sqlMapConfig.xml)及datasource配置文件(db.properties)
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis
username=root
password=root
sqlMapConfig.xml
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN“ "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 外部引入配置 -->
<properties resource="db.properties"/>
<!-- 类型别名,方便后面的UserMapper.xml中使用 -->
<typeAliases>
<!-- 这种可以自定义别名 -->
<!--typeAlias alias="User" type="pojo.User"-->
<!-- 扫描全包,别名为包下类名 -->
<package name="pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- 映射器 -->
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
<!--mapper class="mapper.UserMapper"-->
<!--package name="mapper"-->
</mappers>
</configuration>
编写MyBatis工具类Util(MyBatis.util)
public class MybatisUtil {
// 提升这个变量的作用域
private static SqlSessionFactory sqlSessionFactory;
static {
try {
// 加载核心配置文件
String resource = "mybatis-Config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
// SqlSession实例的geter方法
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
1.3 junit测试
- 增(需要提交事务)
public class addUser {
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(3,"y","13245"));
sqlSession.commit();
sqlSession.close();
}
}
- 删(需要提交事务)
@Test
public void delUserById(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.delUserById(3);
sqlSession.commit();
sqlSession.close();
}
- 查
@Test
public void findAll(){
// 获取Session
SqlSession session = MybatisUtil.getSqlSession();
// 使用getMapper方式
UserMapper mapper = session.getMapper(UserMapper.class);
// 执行SQL语句
List<User> userList = mapper.findAll();
for (User user : userList) {
System.out.println(user);
}
// 关闭Session
session.close();
}
- 改(需要提交事务)
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.clas
mapper.updateUser(new User(2, "x", "12344"));
sqlSession.commit();
sqlSession.close();
}
模糊查询(字符串用%%包围)
@Test
public void userList(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserLike("%y%");
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
使用map参数(优点:使用map你需要什么参数就put什么参数,不需要像实体类那样new一个需要写出去全部属性)
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<>();
map.put("userId",5);
map.put("passWord","1234);
mapper.addUser2(map);
sqlSession.commit();
sqlSession.close();
}
1.4 注意问题:
每个操作使用不同的标签,比如插入语句使用insert标签
- 在映射文件中使用parameterType属性指定参数数据类型,resultType属性指定返回类型
- Sql语句中可以使用#{实体属性名}方式引用实体中的属性值
- 插入、修改、删除操作涉及数据库数据变化,所以要使用sqlSession对象显示的提交事务,即sqlSession.commit()
- 最后关闭,sqlSession.close()