java dao |---SwordDao entity |---Sword resources mapper |---Sword.xml application.yml
1.application.yml
#坑点0 配置mybatis的xml位置mybatis: mapper-locations: classpath:mapper/*.xml2.新建dao文件夹,新建dao接口:SwordDao.java
public interface SwordDao {
List 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语句4.将dao添加扫包范围:com.toly1994.toly_mybatis.TolyMybatisApplicationinsert into sword(name,atk,hit,crit,attr_id,type_id) values (#{name},#{atk},#{hit},#{crit},#{attr_id},#{type_id}) SELECT*FROM sword WHERe NAME=#{name}
//坑点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)@SpringBootTestpublic class SwordDaoTest { @Autowired
private SwordDao mSwordDao; @Test
public void findALL() {
List 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是干嘛的,其实是两张关联表
联合查询.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}修改查询所有的SQL语句测试:可见两张表和主表连在一起了
@Test
public void findALL() {
List 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



