Mybatis 整合流程
① 添加MyBatis的依赖
② 创建数据库表
③ 编写pojo实体类
④ 编写映射文件UserMapper.xml
⑤ 编写核心文件mybatis-config.xml
⑥ 编写测试类**
编写 pojo 实体类 (设计相应的数据库)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id; //id
private String name; //姓名
private String pwd; //密码
}
UserMapper 接口实现
List<User> getUserLike(String value);
//查询全部用户
List<User> findAll();
//根据id查询用户
User selectUserById(int id);
User getUserById(Map<String,Object> map);// 万能的map
//添加一个用户
int addUser(User user);
int addUser2(Map<String,Object> map);// 万能的map
//修改一个用户
int updateUser(User user);
//删除一个用户
int deleteUser(int id);
// 分页
List<User> Limit(Map<String,Integer> map);
List<User> RowBounds();
UserMapper.xml (dao包下面)
<!--查询操作
<select id="findAll" resultType="com.hp.pojo.User"> 下面同理可见-->
<!--模糊查询-->
<select id="getUserLike" resultType="User">
select *from user where pwd like "%"#{value}"%"
</select>
<!--查询全部操作-->
<select id="findAll" resultType="user">
select * from user
</select>
<!--插入操作-->
<insert id="addUser" parameterType="user">
insert into user values(#{id},#{username},#{password})
</insert>
<!--万能的 Map 操作-->
<insert id="addUser2" parameterType="map">
insert into user values (#{userid1111},#{userName},#{password})
</insert>
<!--删除操作-->
<delete id="delete" parameterType="int">
delete from user where id=#{id}
</delete>
<!--修改操作-->
<update id="update" parameterType="user">
update user set username=#{username},password=#{password} where id=#{id}
</update>
<!--根据id进行查询-->
<select id="findById" resultType="user" parameterType="int">
select * from user where id=#{id}
</select>
<!--分页 结果集映射-->
<resultMap id="UserMap" type="User"/>
<select id="Limit" parameterType="map" resultMap="UserMap">
select * from user limit #{startIndex},#{pageSize}
</select>
<!--分页 方法2-->
<select id="RowBounds" resultType="User">
select * from user
</select>
mybatis-config.xml (Resources资源目录下)
<?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>
<!--通过properties标签加载外部properties文件-->
<properties resource="db.properties"/>
<!--引入日志工厂-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!-- 设置驼峰命名规则-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!--自定义别名-->
<typeAliases>
<typeAlias type="com.hp.pojo.User" alias="user"/>
</typeAliases>
<!--数据源环境-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--加载映射文件-->
<mappers>
<!--告诉 mybatis 要执行的 sql 语句的位置 引入外部xml文件-->
<mapper resource="com/hp/dao/mapper.xml"/>
</mappers>
</configuration>
抽出 MyBatisUtil 工具类 简化测试代码(Util包下面)
public class MyBatisUtil {
//定义 SqlSessionFactory
private static SqlSessionFactory factory = null;
static {
//使用 静态块 创建一次 SqlSessionFactory
try {
//读取配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//创建 SqlSessionFactory 对象
factory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (Exception e) {
factory = null;
e.printStackTrace();
}
}
/* 获取 SqlSession 对象 */
public static SqlSession getSqlSession() {
SqlSession sqlsession = null;
if (factory != null) {
sqlsession = factory.openSession();
}
return sqlsession;
}
}
测试类代码
public void findAll() {
SqlSession sqlSession = MyBatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.findAll();
// userList.forEach(System.out::println); 也可以遍历全部输出
for (User user : userList) { // 增强for循环输出
System.out.println(user);
}
sqlSession.close();
}
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
log4j.properties
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/hp.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
Maven 依赖配置
<dependencies>
<!--mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<!-- mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<!-- spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
<scope>provided</scope>
</dependency>
</dependencies>
<!-- Maven静态资源过滤问题-->
<build>
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>