本文主要讲解在Java编程中,spring boot MyBatis xml mapper方式的入门和通过一个简单的例子带新手入门mybaties基本使用。
项目结构图:
#==================DataSource Config Start==================
#name
#spring.datasource.name=test
#url
#spring.datasource.url=jdbc:sqlserver://192.168.xxx.xxx;instanceName=sql_03;DatabaseName=edu;integratedSecurity=false
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
#DriverClass
#spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#DB username
spring.datasource.username=root
#DB password
spring.datasource.password=root
#==================DataSource Config End==================
#==================mybaties Config Start==================
#ORM Bean Package
MyBatis.type-aliases-package=com.leftso.pojo
MyBatis.mapper-locations=classpath:/mapper/*.xml
#==================mybaties Config End ==================
spring boot log简单配置,用于打印sql日志logback-spring.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml" />
<!-- 打印sql -->
<logger name="com.leftso.mapper" level="DEBUG" />
</configuration>
mybaties Java config 配置MyBatiesConfig.java:
package com.leftso.config;
import org.MyBatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;
/**
* mybaties配置扫描mapper路径
*
* @author leftso
*
*/
@Configuration
@MapperScan(basePackages = { "com.leftso.mapper" }) /** 注意,这个注解是扫描mapper接口不是xml文件,使用xml模式必须在配置文件中添加xml的配置 **/
public class MyBatiesConfig {
}
简单测试的用户pojo对象User.java:
package com.leftso.pojo;
/**
* 用户
*
* @author leftso
*
*/
public class User {
private Long id;
private String userName;
private int age;
private String sex;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
User对象的mapper接口:UserMapper.java:
package com.leftso.mapper;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;
import com.leftso.pojo.User;
@Component("userMapper")
public interface UserMapper {
// 新增
int add(User user);
// 修改
int remove(Long id);
// 删除
int update(User user);
// 查一个
User findOne(Long id);
// 查多个
List<User> findList(Map<String, Object> params);
}
mapper对应的xml文件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="com.leftso.mapper.UserMapper">
<!-- 创建一个数据库user表与java中user对象关联的返回映射map -->
<resultMap type="com.leftso.pojo.User" id="UserMap">
<id column="id" property="id" jdbcType="NUMERIC" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="NUMERIC" />
<result column="sex" property="sex" jdbcType="VARCHAR" />
</resultMap>
<!-- 新增 -->
<insert id="add" parameterType="com.leftso.pojo.User"
useGeneratedKeys="true" keyProperty="id">
insert into t_user
<trim prefix="(" suffix=")" suffixOverrides=","><!-- 说明:使用trim的方式组合sql,属性suffixOverrides表示去除末端多余的该属性值(这里是,) -->
user_name,
age,
sex
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
#{name,jdbcType=VARCHAR},
#{age,jdbcType=NUMERIC},<!-- 说明:数字类型都是NUMERIC,没有INT,LONG类型;其他对应类型请参照mybaties官方文档 -->
#{sex,jdbcType=VARCHAR}
</trim>
</insert>
<!-- 删除 -->
<delete id="remove" parameterType="java.lang.Long">
delete from t_user where
id=#{id}
</delete>
<!-- 修改属性 -->
<update id="update" parameterType="com.leftso.pojo.User">
update t_user
<set>
<trim suffixOverrides=",">
<if test="null!=name and ''!=name">
user_name=#{name,jdbcType=VARCHAR},
</if>
<if test="null!=age">
age=#{age,jdbcType=NUMERIC},
</if>
<if test="null!=sex and ''!= sex">
sex=#{sex,jdbcType=VARCHAR},
</if>
</trim>
</set>
where id=#{id,jdbcType=NUMERIC}
</update>
<!-- 查询一个 -->
<select id="findOne" parameterType="java.lang.Long" resultMap="UserMap">
select * from t_user where id=#{id}
</select>
<!-- 查询多个 -->
<select id="findList" parameterType="java.util.Map" resultMap="UserMap">
select * from t_user where 1=1
<if test="null!=name and '' != name">
and user_name like '%${name}%'
</if>
<if test=" sex != null and '' != sex">
and sex = #{sex}
</if>
<if test="age > 0">
and age <![CDATA[ >=]]>#{age} <!-- 说明:在xml里面大于小于大于等于需要逆转 -->
</if>
</select>
</mapper>
单元测试类:
package com.leftso;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.leftso.mapper.UserMapper;
import com.leftso.pojo.User;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
Logger log = LoggerFactory.getLogger(getClass());
@Autowired
UserMapper userMapper;
// @Test
public void add() {
try {
User user = new User();
user.setUserName("测试用户名");
user.setAge(25);
user.setSex("男");
log.info("新增前ID:" + user.getId());
userMapper.add(user);
log.info("新增后ID:" + user.getId());
} catch (Exception e) {
e.printStackTrace();
}
}
// @Test
public void remove() {
try {
userMapper.remove(2l);
} catch (Exception e) {
e.printStackTrace();
}
}
// @Test
public void update() {
try {
User user = new User();
user.setId(3l);
user.setUserName("我是修改");
user.setAge(2);
userMapper.update(user);
} catch (Exception e) {
e.printStackTrace();
}
}
// @Test
public void findOne() {
try {
User user = userMapper.findOne(3l);
log.info("\nName:" + user.getUserName() + "\nAge:" + user.getAge() + "\nSex:" + user.getSex());
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void findList() {
try {
Map<String, Object> params = new HashMap<String, Object>();
params.put("name", "我");
params.put("age", 3);
List<User> list = userMapper.findList(params);
for (User user : list) {
log.info("\nName:" + user.getUserName() + "\nAge:" + user.getAge() + "\nSex:" + user.getSex());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
源码下载:
GitHub:https://github.com/leftso/demo-spring-boot-mybaties3
https://www.leftso.com/article/133.html