<dependency>
<groupId>org.springframework.datagroupId>
<artifactId>spring-data-jpaartifactId>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.hibernategroupId>
<artifactId>hibernate-entitymanagerartifactId>
<version>5.4.32.Finalversion>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.48version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.3version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>5.1.12.RELEASEversion>
dependency>
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.huwc.dao")
public class AppConfig {
//数据源
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///test?useSSL=false&allowPublicKeyRetrieval=true");
dataSource.setUsername("root");
dataSource.setPassword("password");
return dataSource;
}
//entityManager管理器
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);//ddl处理规则,没有表的话,则进行自动创建
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.huwc.pojo");//扫描的pojo的包
factory.setDataSource(dataSource());
return factory;
}
//事务管理器,使用JpaTransactionManager
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory);
return txManager;
}
}
@Entity//表明是一个实体类
@Table(name = "t_customer")//表明
public class Customer {
@Id//主键
@Column(name = "id")//列名
@GeneratedValue(strategy = GenerationType.IDENTITY)//主键生成策略
private Integer id ;
@Column(name = "name")
private String name ;
@Column(name = "address")
private String address ;
@Override
public String toString() {
return "Customer{" +
"id=" + id +
", name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public interface CustomerDao extends CrudRepository<Customer, Integer> {
}
@ContextConfiguration(classes = AppConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringDataTest {
@Autowired
private CustomerDao customerDao ;
@Test
public void test_Save(){
Customer customer = new Customer();
customer.setName("huwenchao");
customer.setAddress("wuhu");
System.out.println(customerDao.save(customer));
}
}
以上可以看出,Spring Data JPA,使得程序员对DAO层的处理非常简单,只要简单声明一个接口,并继承CrudRepository,就可以完全获得对数据库表的增删改查的处理,CrudRepository的源码如下:
@NoRepositoryBean
public interface CrudRepository<T, ID> extends Repository<T, ID> {
/**
* Saves a given entity. Use the returned instance for further operations as the save operation might have changed the
* entity instance completely.
*
* @param entity must not be {@literal null}.
* @return the saved entity; will never be {@literal null}.
* @throws IllegalArgumentException in case the given {@literal entity} is {@literal null}.
* @throws OptimisticLockingFailureException when the entity uses optimistic locking and has a version attribute with
* a different value from that found in the persistence store. Also thrown if the entity is assumed to be
* present but does not exist in the database.
*/
<S extends T> S save(S entity);
/**
* Saves all given entities.
*
* @param entities must not be {@literal null} nor must it contain {@literal null}.
* @return the saved entities; will never be {@literal null}. The returned {@literal Iterable} will have the same size
* as the {@literal Iterable} passed as an argument.
* @throws IllegalArgumentException in case the given {@link Iterable entities} or one of its entities is
* {@literal null}.
* @throws OptimisticLockingFailureException when at least one entity uses optimistic locking and has a version
* attribute with a different value from that found in the persistence store. Also thrown if at least one
* entity is assumed to be present but does not exist in the database.
*/
<S extends T> Iterable<S> saveAll(Iterable<S> entities);
/**
* Retrieves an entity by its id.
*
* @param id must not be {@literal null}.
* @return the entity with the given id or {@literal Optional#empty()} if none found.
* @throws IllegalArgumentException if {@literal id} is {@literal null}.
*/
Optional<T> findById(ID id);
/**
* Returns whether an entity with the given id exists.
*
* @param id must not be {@literal null}.
* @return {@literal true} if an entity with the given id exists, {@literal false} otherwise.
* @throws IllegalArgumentException if {@literal id} is {@literal null}.
*/
boolean existsById(ID id);
/**
* Returns all instances of the type.
*
* @return all entities
*/
Iterable<T> findAll();
/**
* Returns all instances of the type {@code T} with the given IDs.
*
* If some or all ids are not found, no entities are returned for these IDs.
*
* Note that the order of elements in the result is not guaranteed.
*
* @param ids must not be {@literal null} nor contain any {@literal null} values.
* @return guaranteed to be not {@literal null}. The size can be equal or less than the number of given
* {@literal ids}.
* @throws IllegalArgumentException in case the given {@link Iterable ids} or one of its items is {@literal null}.
*/
Iterable<T> findAllById(Iterable<ID> ids);
/**
* Returns the number of entities available.
*
* @return the number of entities.
*/
long count();
/**
* Deletes the entity with the given id.
*
* If the entity is not found in the persistence store it is silently ignored.
*
* @param id must not be {@literal null}.
* @throws IllegalArgumentException in case the given {@literal id} is {@literal null}
*/
void deleteById(ID id);
/**
* Deletes a given entity.
*
* @param entity must not be {@literal null}.
* @throws IllegalArgumentException in case the given entity is {@literal null}.
* @throws OptimisticLockingFailureException when the entity uses optimistic locking and has a version attribute with
* a different value from that found in the persistence store. Also thrown if the entity is assumed to be
* present but does not exist in the database.
*/
void delete(T entity);
/**
* Deletes all instances of the type {@code T} with the given IDs.
*
* Entities that aren't found in the persistence store are silently ignored.
*
* @param ids must not be {@literal null}. Must not contain {@literal null} elements.
* @throws IllegalArgumentException in case the given {@literal ids} or one of its elements is {@literal null}.
* @since 2.5
*/
void deleteAllById(Iterable<? extends ID> ids);
/**
* Deletes the given entities.
*
* @param entities must not be {@literal null}. Must not contain {@literal null} elements.
* @throws IllegalArgumentException in case the given {@literal entities} or one of its entities is {@literal null}.
* @throws OptimisticLockingFailureException when at least one entity uses optimistic locking and has a version
* attribute with a different value from that found in the persistence store. Also thrown if at least one
* entity is assumed to be present but does not exist in the database.
*/
void deleteAll(Iterable<? extends T> entities);
/**
* Deletes all entities managed by the repository.
*/
void deleteAll();
}
public interface CustomerDao extends CrudRepository<Customer, Integer> {
@Query(" from Customer where name = :name and address = :address")
public List<Customer> getByNameAndAddress(@Param("name") String name, @Param("address") String address);
}
测试代码:
@Test
public void test_Hql(){
List<Customer> customers = customerDao.getByNameAndAddress("huwenchao", "wuhu");
for (Customer customer : customers) {
System.out.println("customer = " + customer);
}
}