一、SpringData簡介
二、開發第一個SpringData程序
1、創建一個普通maven,過程省略(不懂可見maven的文章)
2.修改pox.xml的文件內容
<!--Mysql 驅動包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.9.Final</version>
</dependency>
3、定義全局文件SpringData.xml文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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"
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/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.mingde"/>
<!--1、 配置數據源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///springdata"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</bean>
<!-- 2、配置實體類管理工廠 -->
<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.mingde"/>
<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.配置jpa:repositories -->
<jpa:repositories base-package="com.mingde" entity-manager-factory-ref="entityManagerFactory"/>
</beans>
4、實體類
package com.mingde.po;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int sid;
private String sname;
private String sex;
private int age;
private String addr;
/*** get、set和toString 作者在此省略 **/
}
5、dao層:自定義方法的命名規則
public interface StudentRepository extends Repository<Student, Integer> {//參數一:要映射的類,參數二:該表的主鍵的類型
/** 這裏只需寫接口,不需要有實現類 **/
/*** 下面的方法名是按照下面的‘自定義方法的命名規則表’來命名的,不是隨便亂命名的 ***/
//根據姓名查詢學生信息
List<Student> findBySname(String sname)throws Exception;
//模糊查詢
List<Student> findBySnameLike(String sname)throws Exception;
//查詢性別和年齡大於多少歲的
List<Student> findBySexAndAgeGreaterThan(String sex ,int age)throws Exception;
//查詢一某個字開頭的(如某個地址是以‘上’開頭的:上海)
List<Student> findByAddrStartingWith(String saddr)throws Exception;
//查詢指定性別並且按年齡升序排序
List<Student> findBySexOrderByAge(String sex)throws Exception;
}
自定義方法的命名規則表:
6、測試類
import java.util.List;
import org.junit.Before;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mingde.dao.StudentRepository;
import com.mingde.po.Student;
import com.mingde.service.StudentService;
public class Test {
private ApplicationContext ac;
private StudentRepository sr;
@Before
public void setUp() throws Exception {
ac=new ClassPathXmlApplicationContext("SpringData.xml");
sr=ac.getBean(StudentRepository.class);
}
@org.junit.Test
public void test() {
System.out.println("開始了");
}
//查詢叫‘張三’的所有學生
@org.junit.Test
public void test2() throws Exception {
List<Student> findBySname = sr.findBySname("張三");
System.out.println(findBySname);
}
//模糊查詢姓名帶‘張’的所有學生
@org.junit.Test
public void test3() throws Exception {
List<Student> findBySname = sr.findBySnameLike("%張%");
System.out.println(findBySname);
}
//查詢所有男生並且年齡大於12歲的
@org.junit.Test
public void test4() throws Exception {
List<Student> findBySname = sr.findBySexAndAgeGreaterThan("男",12);
System.out.println(findBySname);
}
//查詢地址中以‘上’開頭的
@org.junit.Test
public void test5() throws Exception {
List<Student> findBySname = sr.findByAddrStartingWith("上");
System.out.println(findBySname);
}
//查詢指定性別並且按年齡升序排序
@org.junit.Test
public void test6() throws Exception {
List<Student> findBySname = sr.findBySexOrderByAge("男");
System.out.println(findBySname);
}
}
三、利用註解@Query及@Modifying來進行開發
1.pom.xml和SpringData.xml和實體類同上
2.定義Dao層
package com.mingde.dao;
import java.util.List;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.RepositoryDefinition;
import org.springframework.data.repository.query.Param;
import com.mingde.po.Student;
//自主命名查詢方法
@RepositoryDefinition(domainClass=Student.class,idClass=Integer.class) //可以替代下面的extends。。
public interface StudentRepository2 /*extends Repository<Student, Integer>*/{
//查詢所有
@Query("select st from Student st") //這裏不能寫成select * from student,不能擁有*號
public List<Student> findAll() throws Exception;
//根據姓名進行模糊查詢
@Query("select st from Student st where st.sname like %?1%")
public List<Student> findByWords(String words) throws Exception;
//修改學生
@Modifying //代表可以修改
@Query("update Student st set st.sname=:sname,st.addr=:addr where st.sid=:sid")
public void updateStudent(@Param("sname")String sname,
@Param("addr")String addr,
@Param("sid") int sid) throws Exception;
}
3、定義Service層
package com.mingde.service;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mingde.dao.StudentRepository2;
@Service
public class StudentService {
@Autowired //在junit是不可以使用該註解的,因爲spring無法掃描Junit的test文件
private StudentRepository2 sr;
@Transactional
public void updateStudent(String sname,String addr,int sid) throws Exception {
sr.updateStudent(sname, addr, sid);
}
}
4、測試類
package com.mingde.test;
import java.util.List;
import org.junit.Before;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mingde.dao.StudentRepository;
import com.mingde.dao.StudentRepository2;
import com.mingde.po.Student;
import com.mingde.service.StudentService;
public class Test {
private ApplicationContext ac;
private StudentRepository2 sr2;
@Before
public void setUp() throws Exception {
ac=new ClassPathXmlApplicationContext("SpringData.xml");
sr2=ac.getBean(StudentRepository2.class);
}
/** 利用註解@Query及@Modifying **/
@org.junit.Test
public void test7() throws Exception {
List<Student> findAll = sr2.findAll();
System.out.println(findAll);
}
public static void main(String[] args) throws Exception {
ApplicationContext ac2=new ClassPathXmlApplicationContext("SpringData.xml");
StudentRepository2 sr2=ac2.getBean(StudentRepository2.class);
StudentService ss=ac2.getBean(StudentService.class);
/*//查詢所有學生
List<Student> findAll = sr2.findAll();
System.out.println(findAll);
//模糊查詢學生
List<Student> findByWords = sr2.findByWords("張");
System.out.println(findByWords);*/
//修改學生信息
ss.updateStudent("鄭秋冬", "杭州", 1002);
}
}
注意:@Query和@Modifying不能進行添加(insert)操作