创建maven项目并添加依赖
org.springframework.boot spring-boot-starter-parent 2.0.3.RELEASE junit junit 3.8.1 test org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-jpa com.microsoft.sqlserver sqljdbc4 4.0
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{ }
启动项目访问localhost:8080/index
Copyright © 2023 leiyu.cn. All Rights Reserved. 磊宇云计算 版权所有 许可证编号:B1-20233142/B2-20230630 山东磊宇云计算有限公司 鲁ICP备2020045424号
磊宇云计算致力于以最 “绿色节能” 的方式,让每一位上云的客户成为全球绿色节能和降低碳排放的贡献者