创建一个maven项目
添加依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cn</groupId> <artifactId>springboot-jdbc</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>springboot-jdbc Maven Webapp</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> </parent> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>sqljdbc4</artifactId> <version>4.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.5</version> </dependency> <!-- <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.1</version> </dependency> --> </dependencies> <build> <finalName>springboot-jdbc</finalName> </build> </project>
application.properties配置 我这里用的是SQLserver
1.spring.datasource.url=jdbc:sqlserver://ip:port;DatabaseName=数据库名 spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver spring.datasource.username=sa spring.datasource.password=123
项目启动类
这里添加了一个@MapperScan注解,但是我看别人的项目不加这个注解也可以,只用ComponentScan扫com.vhukze这个二级的包就可以了 ,我的不加不行,不加扫不到mapper包。对于我这个初学者来说 ,还不知道具体原因
@SpringBootApplication @ComponentScan(basePackages = "com.vhukze") @MapperScan("com.vhukze.mapper") public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
项目结构
controller层
@RestController public class JdbcDemoController { @Autowired private JdbcService service; @RequestMapping("/mybatis") public void Jdbc() { service.insert(); } }
service层
@Service public class JdbcServiceImpl implements JdbcService { @Autowired private UserMapper mapper; public void insert() { mapper.insert(); } }
dao层
@Mapper public interface UserMapper { @Insert("insert into userDemo values('3','2')") void insert(); }