创建maven项目并添加依赖
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </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-data-jpa</artifactId> </dependency> <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>sqljdbc4</artifactId> <version>4.0</version> </dependency> </dependencies>
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
启动类
@EnableJpaRepositories是扫描dao层
@EntityScan是扫描实体类包
package com.vhukze.App; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication(scanBasePackages= "com.vhukze.controller") @EnableJpaRepositories(basePackages="com.vhukze.repository") @EntityScan("com.vhukze.entity") public class App { public static void main( String[] args ) { SpringApplication.run(App.class , args); } }
实体类
@Entity注解中的name的值是实体类对应的表名,最好是使用下划线命名规范
@Id是主键,@Column是列
注意:这些注解都是反射包中的
package com.vhukze.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @Entity(name="user_demo") public class UserDemo { @Id @Column private String username; @Column private String password; public UserDemo() { } public UserDemo(String username, String password) { super(); this.username = username; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "UserDemo [username=" + username + ", password=" + password + "]"; } }
controller层
@RestController public class UserController { @Autowired private UserRepository repository; @RequestMapping("index") public String index() { repository.save(new UserDemo("刘海柱","2")); return "success"; } }
dao层 啥也没有 就继承了个接口
1.@Repository public interface UserRepository extends JpaRepository<UserDemo,String>{ }
启动项目访问localhost:8080/index