此篇接上篇:SpringBoot-15-之整合MyBatis-注解篇+分页
0.项目结构
java
dao
|---SwordDao
entity
|---Sword
resources
mapper
|---Sword.xml
application.yml
1.application.yml
#坑点0 配置mybatis的xml位置
mybatis:
mapper-locations: classpath:mapper/*.xml
2.新建dao文件夹,新建dao接口:SwordDao.java
public interface SwordDao {
List<Sword> findALL();
Sword findByName(@Param("name") String name);
//坑点1 java没有保存形参的记录,所以多参数用户@Param("name")起名字,不然无法识别
int insert(@Param("name") String name,
@Param("atk") Integer atk,
@Param("hit") Integer hit,
@Param("crit") Integer crit,
@Param("attr_id") Integer attr_id,
@Param("type_id") Integer type_id
);
}
3.在resources下新建mapper文件夹,再建Sword.xml文件,为dao层提供SQL语句
<?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">
<!--坑点2:命名空间指向对应dao类名-->
<mapper namespace="com.toly1994.toly_mybatis.dao.SwordDao">
<!--坑点3:id为dao中相应方法名-->
<insert id="insert">
insert into sword(name,atk,hit,crit,attr_id,type_id)
values (#{name},#{atk},#{hit},#{crit},#{attr_id},#{type_id})
</insert>
<!--坑点4:返回实体或实体集合时 resultType 指向对应实体类名-->
<select id="findByName" resultType="com.toly1994.toly_mybatis.entity.Sword">
SELECT*FROM sword WHERE NAME=#{name}
</select>
<select id="findALL" resultType="com.toly1994.toly_mybatis.entity.Sword">
SELECT*FROM sword
</select>
</mapper>
4.将dao添加扫包范围:com.toly1994.toly_mybatis.TolyMybatisApplication
//坑点5:将dao添加扫包范围
@MapperScan(basePackages = {"com.toly1994.toly_mybatis.mapper","com.toly1994.toly_mybatis.dao"})
5.单元测试:test文件夹下
com.toly1994.toly_mybatis.dao.SwordDaoTest
@RunWith(SpringRunner.class)
@SpringBootTest
public class SwordDaoTest {
@Autowired
private SwordDao mSwordDao;
@Test
public void findALL() {
List<Sword> all = mSwordDao.findALL();
System.out.println(all.get(5));
//Sword(id=6, name=风跃, atk=9020, hit=10, crit=10, attr_id=2, type_id=2)
}
@Test
public void findByName() {
Sword 赤凰 = mSwordDao.findByName("赤凰");
System.out.println(赤凰);
//Sword(id=13, name=赤凰, atk=0, hit=100, crit=5, attr_id=1, type_id=2)
}
@Test
public void insert() {
int insert = mSwordDao.insert("尤恨", 4000, 100, 100, 1, 1);
System.out.println(insert);//1
}
}
6.联合查询:可能会疑惑attr_id和type_id是干嘛的,其实是两张关联表
修改实体类两个字段:
@Data//=@Getter +@Setter
public class Sword {
private Integer id;
private String name;
private Integer atk;
private Integer hit;
private Integer crit;
private String type_name;//改为String
private String attr;//改为String
}
修改查询所有的SQL语句
<select id="findALL" resultType="com.toly1994.toly_mybatis.entity.Sword">
SELECT id,name,atk,hit,crit,type_name,attr FROM sword AS s
INNER JOIN sword_type AS t ON s.type_id = t.type_id
INNER JOIN sword_attr AS a ON s.attr_id = a.attr_id;
</select>
测试:可见两张表和主表连在一起了
@Test
public void findALL() {
List<Sword> all = mSwordDao.findALL();
System.out.println(all.get(5));
//Sword(id=6, name=风跃, atk=9020, hit=10, crit=10, type_name=仙界, attr=木)
}