注解配置
application.yml配置
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/springdemo?useUnicode=true&characterEncoding=utf8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
配置driver-class-name,会提示找不到Driver这个类,因为jdbc jar 包的scope 设置为runtime,改为compile就行。
编写Mapper 类
@Mapper
public interface BookMapper {
@Select("select * from book where id = #{id} ")
Book queryBookById(@Param("id") Integer id);
//int insertBook(Book book); 只能细化参数
@Insert("insert into book values (#{name},#{writer},#{introduction})")
int insertBook(String name,String writer,String introduction);
@Update("update book set name = #{name} where id = #{id}")
int updateBook(@Param("id") Integer id,@Param("name") String name);
}
service类,直接注入
这里mapper,提示下滑线,不用管
@Service
public class BookService {
@Autowired
private BookMapper mapper;
public Book findBookById(Integer id ){
return mapper.queryBookById(id);
}
}
测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisdemoApplicationTests {
@Autowired
private BookService service;
@Test
public void contextLoads() {
Book book = service.findBookById(1);
System.out.println(book.getName());
}
}
xml方式
application.yml 增加一段配置,指定mapper.xml的位置
#设置mapper.xml的位置
mybatis:
mapper-locations: classpath:mapper/*.xml
mapper.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.example.mybatisdemo.dao.BookMapper">
<select id="queryBookById" parameterType="int" resultType="com.example.mybatisdemo.domain.Book">
select * from book where id = #{id}
</select>
</mapper>
mapper类
@Mapper
public interface BookMapper {
Book queryBookById( Integer id);
}
service层注入使用
@Service
public class BookService {
@Autowired
private BookMapper mapper;
public Book findBookById(Integer id ){
return mapper.queryBookById(id);
}
}