spring boot 与 mybatis集合创建项目

1,建立项目在pom.xml导入jar



	4.0.0

	com.qxmof
	springutil
	0.0.1-SNAPSHOT
	jar

	springutil
	Demo project for Spring Boot

	
		org.springframework.boot
		spring-boot-starter-parent
		2.0.3.RELEASE
		 
	

	
		5.1.38
		UTF-8
		UTF-8
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		
        
		    org.mybatis.spring.boot
		    mybatis-spring-boot-starter
		    1.3.2
		
        
			mysql
			mysql-connector-java
			${mysql-connector.version}
		
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
				
				
                    
                        org.springframework
                        springloaded
                        1.2.5.RELEASE
                    
                
                
			
		
	



2,数据库配置

server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/springboot
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.database=MYSQL
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

mybatis设置

3,设置spring boot启动器初始化加载

@SpringBootApplication
@MapperScan(basePackages = {"com.qxmof.springutil.test.mapper","com.qxmof.springutil.test.service"})
public class SpringutilApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringutilApplication.class, args);
	}
}

此处@MapperScan是加载时需要注入的包路径(建议使用注解在mapper文件上注解@Mapper将文件注入)

在配置类上添加以上注解,可以扫描dao包中的所有接口,替代在每个dao中写@Mapper注解,不过这样会提高耦合度。而@Mapper可以与dao自成一体,与@Controller、@Service遥相呼应,整体结构更优雅

@Mapper:声明一个mybatis的dao接口,会被spring boot扫描到

4,Mapper接口类

@Mapper
public interface TestMapper {

	@Select("select * from es_test")
	Test getById();
	
	@Options(useGeneratedKeys= true,keyProperty = "id")//需要返回id时这样注解
	int insertTest(Test test);
}

此mapper类中sql用的注解格式,也可以使用xml格式

4.1xml格式sql




    
        
        
        
    
    
    
    	insert into es_test (name) value (#{name}); 
    

xml和注解格式的sql选择其一即可,建议选择注解格式

5,实现层

@Service
public class ServiceTest implements IServiceTest {

	@Autowired
	private TestMapper testMapper;
	
	
	@Override
	public Test getTest1() {
		return testMapper.getById();
	}

}

6,接口层

public interface IServiceTest {

    Test getTest1();
}

至此最简单的一个spring boot加mybatis项目构建完成

你可能感兴趣的:(spring,boot,mybatis)