基础

基础

Spring data 提供一个核心接口 CrudRepository 用来提供访问数据库的基本方法,T是访问数据库的实体类,ID是数据库主键数据类型

public interface CrudRepository extends Repository {
 
   S save(S entity);      ①
 
  Optional findById(ID primaryKey); ②
 
  Iterable findAll();               ③
 
  long count();                        ④
 
  void delete(T entity);               ⑤
 
  boolean existsById(ID primaryKey);   ⑥
 
  // … more functionality omitted.
}

① 保存数据
② 根据ID值查找数据
③ 返回所有数据
④ 返回数据的数量
⑤ 删除提供的数据
⑥ 提供的数据是否存在

Spring Data 已经实现了接口的方法,在使用中,只需要提供继承CrudRepository的接口,不需要自己实现相同的方法

下面进行测试

  1. 创建数据表

    CREATE DATABASE jpa_demo;
    USE jpa_demo;
    CREATE TABLE t_user(
        id BIGINT PRIMARY KEY AUTO_INCREMENT,
        firstName VARCHAR(20) NOT NULL,
        lastName VARCHAR(20) NOT NULL
    ) ENGINE = INNODB;
    
  2. 配置Spring Data,这里采用JavaConfig配置

    @Configuration                                   // 这里声明这个文件是配置文件
    @EnableJpaRepositories({"com.lee.repository"})   // 这里制定repository所在的包(package)
    public class DataSourceConfig {
     
      @Bean
      public DataSource dataSource() {
          Properties prop = new Properties();
          DriverManagerDataSource ds = new DriverManagerDataSource();
          
          try {
              String path = getClass().getClassLoader().getResource("db.properties").getPath();
     
              FileInputStream in = new FileInputStream(path);
              prop.load(in);
     
              String driver = prop.getProperty("driver");
              String url = prop.getProperty("url");
              String username = prop.getProperty("uname");
              String password = prop.getProperty("pass");
     
              ds.setDriverClassName(driver);
              ds.setUrl(url);
              ds.setUsername(username);
              ds.setPassword(password);
              in.close();
          } catch (FileNotFoundException e) {
     
          } catch (IOException e) {
     
          }
          
          return ds;
      }
     
      // JPA Hibernate
      @Bean
      public JpaVendorAdapter jpaVendorAdapter() {
         HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
         adapter.setDatabase(Database.MYSQL);
         adapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect");
         adapter.setShowSql(true);
         adapter.setGenerateDdl(false);
       
         return adapter;
      }
          
      @Bean
      public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
         LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
         emfb.setDataSource(dataSource);
         emfb.setJpaVendorAdapter(jpaVendorAdapter);
         emfb.setPackagesToScan("com.lee.entity");
       
         return emfb;
      }
       
      @Bean
      pblic PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
         return new JpaTransactionManager(entityManagerFactory);
      }
          
    }   
    
  3. 创建Entity,Entity需要提供getter, setter方法,用于关联数据表中的对应字段

@Entity                    // 声明这个类是实体类(Entity)
@Table(name = "t_user")    // 指定关联的数据表的名称
public class User {
    private Long id;
    private String firstName;
    private String lastName;
 
    public User() {
        this("testFirstName", "testLastName");
    }
 
    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
 
    @Id                   // 声明这个属性是数据库中的ID字段
    @GeneratedValue       // 声明这个ID值是自增长(数据库中 AUTO_INCREMENT)
    public Long getId() {
        return id;
    }
 
    public void setId(Long id) {
        this.id = id;
    }
 
    @Column(name = "firstName")    // 在getter方法声明这个属性关联数据库中firstName字段
    public String getFirstName() {
        return firstName;
    }
 
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
 
    @Column(name = "lastName")    // 在getter方法声明这个属性关联数据库中lastName字段
    public String getLastName() {
        return lastName;
    }
 
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
 
    /*
    用于打印信息
     */
    @Override
    public String toString() {
        return new StringBuilder()
                .append("id:").append(id)
                .append(", firstName:").append(firstName)
                .append(", lastName:").append(lastName)
                .toString();
    }
}
  1. 创建repository

    public interface UserRepository extends CrudRepository {
    }
    
  2. JUnit测试

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = {DataSourceConfig.class})
    @FixMethodOrder(MethodSorters.NAME_ASCENDING)
    public class UserRepositoryTest {
     
        @Autowired
        private UserRepository userRepository;
        private static User user;
     
        @Test
        public void test_00_init() {
            user = new User("Lee", "Fly");
            System.out.println(user);
        }
     
        @Test
        public void test_01_save() {
            user = userRepository.save(user);
            System.out.println(user);
            assertNotNull(user.getId());
        }
     
        @Test
        public void test_02_update() {
            String rename = "ModifyName";
            user.setFirstName(rename);
            user = userRepository.save(user);
            System.out.println(user);
            assertEquals(rename, user.getFirstName());
        }
     
        @Test
        public void test_10_delete() {
            userRepository.delete(user);
            assertNull(userRepository.findOne(user.getId()));
        }
    }
    

注意:在配置文件中使用了数据库配置信息文件, db.properties, 没有给出, 可以更改成自己的配置方式, 或使用下面的源码
源码地址: https://github.com/LeeSpringFly/learnSpringData
如果运行正常,每一个测试都会显示绿条,表示成功

你可能感兴趣的:(基础)