基礎(chǔ)
Spring data 提供一個核心接口 CrudRepository<T, ID extends Serializable> 用來提供訪問數(shù)據(jù)庫的基本方法募强,T是訪問數(shù)據(jù)庫的實體類负蠕,ID是數(shù)據(jù)庫主鍵數(shù)據(jù)類型
public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {
<S extends T> S save(S entity); ①
Optional<T> findById(ID primaryKey); ②
Iterable<T> findAll(); ③
long count(); ④
void delete(T entity); ⑤
boolean existsById(ID primaryKey); ⑥
// … more functionality omitted.
}
① 保存數(shù)據(jù)
② 根據(jù)ID值查找數(shù)據(jù)
③ 返回所有數(shù)據(jù)
④ 返回數(shù)據(jù)的數(shù)量
⑤ 刪除提供的數(shù)據(jù)
⑥ 提供的數(shù)據(jù)是否存在
Spring Data 已經(jīng)實現(xiàn)了接口的方法,在使用中,只需要提供繼承CrudRepository的接口硫眯,不需要自己實現(xiàn)相同的方法
下面進行測試
-
創(chuàng)建數(shù)據(jù)表
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;
-
配置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); } }
創(chuàng)建Entity,Entity需要提供getter, setter方法泉坐,用于關(guān)聯(lián)數(shù)據(jù)表中的對應(yīng)字段
@Entity // 聲明這個類是實體類(Entity)
@Table(name = "t_user") // 指定關(guān)聯(lián)的數(shù)據(jù)表的名稱
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 // 聲明這個屬性是數(shù)據(jù)庫中的ID字段
@GeneratedValue // 聲明這個ID值是自增長(數(shù)據(jù)庫中 AUTO_INCREMENT)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "firstName") // 在getter方法聲明這個屬性關(guān)聯(lián)數(shù)據(jù)庫中firstName字段
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Column(name = "lastName") // 在getter方法聲明這個屬性關(guān)聯(lián)數(shù)據(jù)庫中l(wèi)astName字段
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();
}
}
-
創(chuàng)建repository
public interface UserRepository extends CrudRepository<User, Long> { }
-
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())); } }
注意:在配置文件中使用了數(shù)據(jù)庫配置信息文件, db.properties, 沒有給出, 可以更改成自己的配置方式, 或使用下面的源碼
源碼地址: https://github.com/LeeSpringFly/learnSpringData
如果運行正常为鳄,每一個測試都會顯示綠條,表示成功