一、所需工具
安装jdk、IntelliJ IDEA和mysql数据库。
二、SpringDataJpa快速起步
开发环境的搭建:
①、在IDEA软件上添加依赖包:在http://mvnrepository.com/网址里面搜索spring-data-jpa,选择1.8.0版本。复制依赖包添加到IDEA的pom.xml文件上面。
<dependencies>
<!--MySQL Driver-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<!--spring data jpa-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.6.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>
</dependencies>
②、在resource文件夹下建立一个beans.xml文件。配置内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!--1:配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="password" value="062988"/>
<property name="url" value="jdbc:mysql://localhost/spring_test"/>
</bean>
<!--2:配置EntityManagerFactory-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="packagesToScan" value="com.example"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<!--3:配置事物管理器-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!--4:配置支持注解的事务-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--5:配置spring data-->
<jpa:repositories base-package="com.example" entity-manager-factory-ref="entityManagerFactory"/>
<context:component-scan base-package="com.example"/>
</beans>
在java文件夹下面建立一个包repository,在该文件夹下建立一个接口EmployeeRepository
/**
* 通过注解方式实现
*/
@RepositoryDefinition(domainClass = Employee.class,idClass = Integer.class)
public interface EmployeeRepository //extends Repository<Employee,Integer> {
{
public Employee findByName(String name);
public Employee findByAge(Integer age);
public Employee findById(Integer id);
//where name like ?% and age <?
public List<Employee> findByNameStartingWithAndAgeLessThan(String name,Integer age);
//where name like ?% and age <?
public List<Employee> findByNameEndingWithAndAgeLessThan(String name,Integer age);
//where name in (?,?....) or age<?
public List<Employee> findByNameInOrAgeLessThan(List<String> names,Integer age);
//where name in (?,?....) and age<?
public List<Employee> findByNameInAndAgeLessThan(List<String> names,Integer age);
@Query("select o from Employee o where id=(select max(id) from Employee t1)")
public Employee getEmployeeByMaxId();
@Query("select o from Employee o where o.name=?1 and o.age=?2")
public List<Employee> queryParams1(String name,Integer age);
@Query("select o from Employee o where o.name=:name and o.age=:age")
public List<Employee> queryParams2(@org.springframework.data.repository.query.Param("name") String name, @org.springframework.data.repository.query.Param("age") Integer age);
@Query("select o from Employee o where o.name like %?1%")
public List<Employee> queryLike1( String name);
@Query("select o from Employee o where o.name like %:name%")
public List<Employee> queryLike2(@org.springframework.data.repository.query.Param("name")String name);
@Query(nativeQuery = true,value = "select count(1) from employee")
public long getCount();
@Modifying
@Query("update Employee o set o.age= :age where o.id = :id")
public void updata(@org.springframework.data.repository.query.Param("id")Integer id, @org.springframework.data.repository.query.Param("age")Integer age);
@Modifying
@Query("delete from Employee o where o.id = :id")
public void delete(@org.springframework.data.repository.query.Param("id")Integer id);
}
/***
* 通过继承Repository接口实现
*/
//public interface EmployeeRepository extends Repository<Employee,Integer> {
// public Employee findByName(String name);
// public Employee findByAge(Integer age);
// public Employee findById(Integer id);
//}
在test文件夹下建立一个包repository,在该文件夹下建立一个测试类EmployeeRepositoryTest.java。
public class EmployeeRepositoryTest {
private ApplicationContext ctx = null;
private EmployeeRepository employeeRepository = null;
@Before
public void setup() {
ctx = new ClassPathXmlApplicationContext("beans-new.xml");
employeeRepository = ctx.getBean(EmployeeRepository.class);
System.out.println("setup");
}
@After
public void tearDown() {
ctx = null;
System.out.println("tearDown");
}
@Test
public void testFindByName() {
Employee employee = employeeRepository.findByName("zhangsan");
System.out.println("id:"+employee.getId()+",name:"+employee.getName()+",age:"+employee.getAge());
}
@Test
public void testFindByAge() {
Employee employee = employeeRepository.findByAge(21);
System.out.println("id:"+employee.getId()+",name:"+employee.getName()+",age:"+employee.getAge());
}
@Test
public void testFindById() {
Employee employee = employeeRepository.findById(1);
System.out.println("id:"+employee.getId()+",name:"+employee.getName()+",age:"+employee.getAge());
}
@Test
public void testFindByNameStartingWithAndAgeLessThan() {
List<Employee> employees = employeeRepository.findByNameStartingWithAndAgeLessThan("test",22);
for(Employee employee:employees) {
System.out.println("id:"+employee.getId()+"," +
"name:"+employee.getName()+
",age:"+employee.getAge());
}
}
@Test
public void testFindByNameEndingWithAndAgeLessThan() {
List<Employee> employees = employeeRepository.findByNameEndingWithAndAgeLessThan("6",23);
for(Employee employee:employees) {
System.out.println("id:"+employee.getId()+"," +
"name:"+employee.getName()+
",age:"+employee.getAge());
}
}
@Test
public void testFindByNameInOrAgeLessThan() {
List<String> names=new ArrayList<String>();
names.add("test1");
names.add("test2");
names.add("test3");
List<Employee> employees = employeeRepository.findByNameInOrAgeLessThan(names,22);
for(Employee employee:employees) {
System.out.println("id:"+employee.getId()+"," +
"name:"+employee.getName()+
",age:"+employee.getAge());
}
}
@Test
public void testFindByNameInAndAgeLessThan() {
List<String> names=new ArrayList<String>();
names.add("test1");
names.add("test2");
names.add("test3");
List<Employee> employees = employeeRepository.findByNameInAndAgeLessThan(names,22);
for(Employee employee:employees) {
System.out.println("id:"+employee.getId()+"," +
"name:"+employee.getName()+
",age:"+employee.getAge());
}
}
@Test
public void testGetEmployeeByMaxId() {
Employee employee = employeeRepository.getEmployeeByMaxId();
System.out.println("id:"+employee.getId()+"," +
"name:"+employee.getName()+
",age:"+employee.getAge());
}
@Test
public void testQueryParams1() {
List<Employee> employees = employeeRepository.queryParams1("lisi",21);
for (Employee employee:employees) {
System.out.println("id:"+employee.getId()+"," +
"name:"+employee.getName()+
",age:"+employee.getAge());
}
}
@Test
public void testQueryParams2() {
List<Employee> employees = employeeRepository.queryParams2("lisi",21);
for (Employee employee:employees) {
System.out.println("id:"+employee.getId()+"," +
"name:"+employee.getName()+
",age:"+employee.getAge());
}
}
@Test
public void testQueryLike1() {
List<Employee> employees = employeeRepository.queryLike1("test");
for (Employee employee:employees) {
System.out.println("id:"+employee.getId()+"," +
"name:"+employee.getName()+
",age:"+employee.getAge());
}
}
@Test
public void testQueryLike2() {
List<Employee> employees = employeeRepository.queryLike2("test1");
for (Employee employee:employees) {
System.out.println("id:"+employee.getId()+"," +
"name:"+employee.getName()+
",age:"+employee.getAge());
}
}
@Test
public void testGetCount() {
long count = employeeRepository.getCount();
System.out.println("count:"+count);
}
}
点击testFindByName右键运行,控制台将打印出根据名字查询到的数据库信息。