MyBatis-xml版本
MyBatis 是一款优秀的持久层框架
MyBatis中文网https://mybatis.net.cn/
添加依赖
<dependencies>
<!--mysql驱动-->
<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.2</version>
</dependency>
<!--测试工具-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<!--扫描包,读取配置文件-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
resources目录下编写配置文件
- db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useSSL&useUnicode=true&charsetEncoding=UTF-8
username=root
password=123
- log4j.properties
# 输出DEBUG级别的日志到console和file
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.console.layout.ConversionPattern=%5p [%t] - %m%n
#输出到文件的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
# 不追加写入:log4j.appender.file.Append = false
# 输出位置
log4j.appender.file.File = ./log/log.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{yyyy-MM-dd HH:mm:ss}][%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
- 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>
<!--引入外部配置文件-->
<properties resource="db.properties">
<!--可以添加属性,遇到相同属性,外部资源优先级高于这里-->
<property name="addr" value="bj"/>
</properties>
<settings>
<!--设置日志实现:STDOUT_LOGGING标准日志工厂-->
<!-- <setting name="logImpl" value="STDOUT_LOGGING"/>-->
<setting name="logImpl" value="LOG4J"/>
<!--开启全局缓存(二级),默认是true-->
<setting name="cacheEnabled" value="true"/>
</settings>
<!--别名设置-->
<typeAliases>
<!--自定义类的别名-->
<typeAlias type="org.example.pojo.User" alias="User"/>
<!--定义包下类的别名:默认是类名(建议首字母小写),要自定义别名可以在类名上加注解:@Alias("别名")-->
<package name="org.example.pojo"/>
</typeAliases>
<!--配置环境:default设置使用哪套环境-->
<environments default="prd">
<environment id="dev">
<!--设置事务类型-->
<transactionManager type="JDBC"></transactionManager>
<!--设置连接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?useSSL&useUnicode=true&charsetEncoding=UTF-8"/>
</dataSource>
</environment>
<environment id="prd">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
<property name="url" value="${url}"/>
</dataSource>
</environment>
</environments>
<!--注册mapper.xml-->
<mappers>
<mapper resource="org/example/dao/UserMapper.xml"/>
</mappers>
</configuration>
实体类
//@Alias("user")
public class User implements Serializable {
private Integer id;
private String username;
private String password;
// getter、setter、tostring、有参构造、无参构造
}
mapper接口
public interface UserMapper {
// xml实现
List<User> getUsers();
// 多参数情况下用注解@Param("占位名")声明
User getUser(@Param("user_name") String username,@Param("pass_word") String password);
User getUserById(Integer id);
int insertUser(User user);
int insertUserBatch(@Param("userList") List<User> userList);
// 常用map做参数
int insertUserAsMap(Map<String,Object> map);
int updateUserById(User user);
int deleteUserById(Integer id);
int deleteUserByIds(Integer[] id);
// 注解实现
@Select("select * from user")
List<User> getUsers2();
}
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" >
<mapper namespace="org.example.dao.UserMapper">
<!--在当前mapper.xml文件中使用二级缓存,实体类必须序列化-->
<!--会话提交或关闭后,数据会存入二级缓存-->
<cache/>
<resultMap id="userMap" type="org.example.pojo.User">
<!--主键用id标签-->
<id column="id" property="id"/>
<!--普通字段用result标签-->
<result column="username" property="username"/>
<result column="password" property="password"/>
<!--对象属性配置,引用其他mapper.xml中配置好的resultMap,实现关联查询-->
<!-- <association property="user" resultMap="userMap"/>-->
<!--一对多-->
<!--<collection property="userList" ofType="user">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
</collection>-->
</resultMap>
<select id="getUsers" resultMap="userMap">
select * from user
<!--特殊符号处理:< > & ' "-->
<!--<![CDATA[
select * from user where id < 10
]]>-->
</select>
<select id="getUser" resultMap="userMap">
select * from user
<where>
<if test="user_name != null and user_name != ''">
and username like concat('%',#{user_name},'%')
</if>
<if test="pass_word != null and pass_word != ''">
and password = #{pass_word}
</if>
<!--choose when otherwise类似switch case default-->
<!--<choose>
<when test="user_name != null and user_name != ''">
and username like concat('%',#{user_name},'%')
</when>
<when test="pass_word != null and pass_word != ''">
and password = #{pass_word}
</when>
<otherwise>
and id = -1
</otherwise>
</choose>-->
</where>
</select>
<select id="getUserById" parameterType="java.lang.Integer" resultType="org.example.pojo.User">
select * from user where id = #{id}
</select>
<!--对象参数可以直接解构,useGeneratedKeys返回生成的主键,返回到keyProperty指定的属性中-->
<insert id="insertUser" keyProperty="id" useGeneratedKeys="true">
insert into user (id,username,password) values(#{id},#{username},#{password})
</insert>
<!--批量新增-->
<insert id="insertUserBatch">
insert into user (id,username,password) values
<foreach collection="userList" item="user" separator=",">
(#{user.id},#{user.username},#{user.password})
</foreach>
</insert>
<!--通过map自定义占位符的命名,万能参数类型-->
<insert id="insertUserAsMap" parameterType="java.util.Map">
insert into user (username,password) values(#{name},#{pwd})
</insert>
<update id="updateUserById" parameterType="org.example.pojo.User">
update user
<set><!--set标签可以去除多余的逗号-->
<if test="username != null and username != ''">
username = #{username},
</if>
<if test="password != null and password != ''">
password = #{password},
</if>
</set>
<where>
<if test="id != null">
and id = #{id}
</if>
</where>
</update>
<delete id="deleteUserById" parameterType="java.lang.Integer">
delete from user where id = #{id}
</delete>
<delete id="deleteUserByIds">
delete from user where id in
<!--delete from user where id in ( ? , ? )-->
<foreach collection="array" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
</mapper>
测试类
public class Test01 {
private SqlSession sqlSession;
@Before
public void before(){
SqlSessionFactory sqlSessionFactory;
try {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
sqlSession = sqlSessionFactory.openSession();
System.out.println("@Before在测试方法执行前执行,可以在此处获取sqlSession");
}
@After
public void after(){
// DML语句需要提交事务
sqlSession.commit();
sqlSession.close();
System.out.println("@After在测试方法完成后执行,可以在此处提交事务,关闭资源");
}
@Test
public void test01() {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// System.out.println(userMapper.getUserById(-3));
// User user = new User(null,"zhaoliu", "12345");
// System.out.println(userMapper.insertUser(user));
// System.out.println(user.getId());
// List<User> userList = new ArrayList<>();
// userList.add(new User(6,"66","666"));
// userList.add(new User(7,"77","777"));
// System.out.println(userMapper.insertUserBatch(userList));
// System.out.println(userMapper.updateUserById(new User(5, "zhao", "12345")));
// System.out.println(userMapper.deleteUserById(-4));
// System.out.println(userMapper.deleteUserByIds(new Integer[]{6,7}));
// Map<String,Object> map = new HashMap<String, Object>();
// map.put("name","chenqi");
// map.put("pwd",1234);
// System.out.println(userMapper.insertUserAsMap(map));
// System.out.println(userMapper.getUser("lisi","12345"));
// System.out.println(userMapper.getUsers());
System.out.println(userMapper.getUsers2());
}
}