关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

springboot集成jpa的Demo

发布时间:2023-07-01 00:28:11

创建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


/template/Home/leiyu/PC/Static