IDEA 创建项目
创建项目.PNG
全注解方式
Mybatis maper的全注解形式,不用dao接口,不用mapper的xml文件,都在一个类里面
/**
* mybatis的dao接口和mapper配置文件的合体
*/
@Mapper
@Repository
public interface CustomerMapper {
@Select("SELECT * FROM customers")
List findAll();
}
application.properties
server.port=8080
server.servlet.context-path=/boot
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
# mysql
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/shpun?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
测试通过
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestspringbootApplicationTests {
@Autowired
private CustomerMapper customerMapper;
@Test
public void testCustomerMapper(){
System.out.println(customerMapper.findAll());
}
}
xml方式
mybatis-config.xml mybatis的配置文件
/p>
"http://mybatis.org/dtd/mybatis-3-config.dtd">
CustomerMapper.xml mapper的xml文件
/p>
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
select * from customers
application.properties
server.port=8888
server.servlet.context-path=/yml
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
# mysql
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/shpun?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
# mybatis
mybatis.type-aliases-package=com.shpun.bean
mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mapper/*.xml
dao 接口
@Mapper
@Repository
public interface CustomerDao{
List selectAllCustomers();
}
测试通过
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestspringbootApplicationTests {
@Autowired
private CustomerDao customerDao;
@Test
public void testCustomerDao(){
System.out.println(customerDao.selectAllCustomers());
}
}
ps:
先前用xml的时候,提示错误找不到dao的bean,在dao上添加
@Mapper
如果是多个dao接口的话,每个都加比较麻烦,可以在SpringBootApplication的java类中添加
@MapperScan("com.shpun.dao")