java dao |---SwordDao entity |---Sword resources mapper |---Sword.xml application.yml
#坑点0 配置mybatis的xml位置mybatis: mapper-locations: classpath:mapper/*.xml
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
);
}
<?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>
//坑点5:将dao添加扫包范围@MapperScan(basePackages = {"com.toly1994.toly_mybatis.mapper","com.toly1994.toly_mybatis.dao"})
@RunWith(SpringRunner.class)@SpringBootTestpublic 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
}
}

联合查询.png
@Data//=@Getter +@Setterpublic 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}
<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=木)
}
作者:张风捷特烈
链接:https://www.jianshu.com/p/e7b98cc68a80
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1806/viewspace-2821052/ ,如需转载,请注明出处,否则将追究法律责任。