一定不要加这段代码 这个注解是排除自动注入 导致mapper注入不进去。
//@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class)
springboot +mybatis
1、注意几个重要注解
bean类中在主键属性中添加@Id
*mapper类不需要添加
@SpringBootApplication
@EnableTransactionManagement // 如果mybatis中service实现类中加入事务注解,需要此处添加该注解
@MapperScan(basePackages = "com.geovis.testDatabase.mapper") // 扫描的是mapper.xml中namespace指向值的包位置
//@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class)
public class TestDatabaseApplication {
public static void main(String[] args) {
//SpringApplication.run(TestDatabaseApplication.class, args);
SpringApplication app = new SpringApplication(TestDatabaseApplication.class);
app.run(args);
}
}
@RestController
@ComponentScan({"******testDatabase.mapper"})
@RequestMapping("/api")
public class UserController {
@Resource
private UserService userServiceImpl;
@GetMapping("/selectByid/{id}")
public User selectByID(@PathVariable Integer id){
User user = userServiceImpl.findByID(id);
return user;
}
}
@Service
@Transactional
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper uMapper;
@Override
public User findByID(int id) {
User user = uMapper.selectByPrimaryKey(id);
return user;
}
}
application.yml配置文件(一定要注意空格,不要多加空格,多加一个都不能启动即使是空行)
server:
port: 9190
session:
timeout: 50
tomcat:
uri-encoding: UTF-8
spring:
datasource:
name: test
url: jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8
username: root
password: 123456
drive-class-name: com.mysql.jdbc.Driver
jpa:
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
temp:
use_jdbc_metadata_defaults: false
mybatis:
type-aliases-package: com.geovis.testDatabase.bean
mapper-locations: classpath:mapperxml/*Mapper.xml
configuration:
map-underscore-to-camel-case: true
default-fetch-size: 500
default-statement-timeout: 80
这里使用mybatis,可以通过数据库反向建立实体类和**mapper.xml。具体见https://blog.csdn.net/qq_18298439/article/details/80499988