1.创建一个jar工程,添加下面的依赖
<properties>
<spring.version>5.0.2.RELEASE</spring.version>
<hibernate.version>5.0.7.Final</hibernate.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<c3p0.version>0.9.1.2</c3p0.version>
<mysql.version>5.1.6</mysql.version>
</properties>
<dependencies>
<!-- junit单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- spring beg -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring对orm框架的支持包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring end -->
<!-- hibernate beg -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.1.Final</version>
</dependency>
<!-- hibernate end -->
<!-- c3p0 beg -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
<!-- c3p0 end -->
<!-- log end -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- spring data jpa 的座标-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- el beg 使用spring data jpa 必须引入 -->
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
<!-- el end -->
<!-- jdk9加入 -->
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
2.创建一个配置文件applicationContext.xml,加入以下代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<context:component-scan base-package="com.baidu" />
<!--配置实体类管理器工厂-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--配置实现Jpa的厂商-->
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
</property>
<!--配置实体类所在的包-->
<property name="packagesToScan" value="com.baidu.pojo"/>
<!--jpa的供应商适配器 -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!--配置是否自动创建数据库表 -->
<property name="generateDdl" value="false" />
<!--指定数据库类型 -->
<property name="database" value="MYSQL" />
<!--数据库方言:支持的特有语法 -->
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
<!--是否显示sql -->
<property name="showSql" value="true" />
</bean>
</property>
<!--jpa的方言 :高级的特性 -->
<property name="jpaDialect" >
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
<property name="jpaProperties" >
<props>
<!--
update:没有表则创建表
create:删除表再创建表
-->
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<!--2.创建数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="root"/>
<property name="password" value="root"/>
<property name="jdbcUrl" value="jdbc:mysql:///jpa" />
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
</bean>
<!--配置dao所在的位置,创建代理对象-->
<jpa:repositories base-package="com.baidu.dao"
transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory"/>
<!--创建事务管理器-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!--开启注解事务-->
<tx:annotation-driven/>
</beans>
3.创建实体类
package com.baidu.pojo;
import javax.persistence.*;
@Entity //表示此类是实体类
@Table(name = "cst_customer") //配置数据库表名
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) //主键生成策略,枚举类型,其它的点进去看
@Column(name = "cust_id") //对应数据库的字段,如果不配则使用属性名当作字段名
private Long custId; //客户的主键
@Column(name = "cust_name")
private String custName;//客户名称
@Column(name="cust_source")
private String custSource;//客户来源
@Column(name="cust_level")
private String custLevel;//客户级别
@Column(name="cust_industry")
private String custIndustry;//客户所属行业
@Column(name="cust_phone")
private String custPhone;//客户的联系方式
@Column(name="cust_address")
private String custAddress;//客户地址
public Long getCustId() {
return custId;
}
public void setCustId(Long custId) {
this.custId = custId;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public String getCustSource() {
return custSource;
}
public void setCustSource(String custSource) {
this.custSource = custSource;
}
public String getCustLevel() {
return custLevel;
}
public void setCustLevel(String custLevel) {
this.custLevel = custLevel;
}
public String getCustIndustry() {
return custIndustry;
}
public void setCustIndustry(String custIndustry) {
this.custIndustry = custIndustry;
}
public String getCustPhone() {
return custPhone;
}
public void setCustPhone(String custPhone) {
this.custPhone = custPhone;
}
public String getCustAddress() {
return custAddress;
}
public void setCustAddress(String custAddress) {
this.custAddress = custAddress;
}
@Override
public String toString() {
return "Customer{" +
"custId=" + custId +
", custName='" + custName + '\'' +
", custSource='" + custSource + '\'' +
", custLevel='" + custLevel + '\'' +
", custIndustry='" + custIndustry + '\'' +
", custPhone='" + custPhone + '\'' +
", custAddress='" + custAddress + '\'' +
'}';
}
}
创建dao
package com.baidu.dao;
import com.itcast.pojo.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
//继承这两个接口之后该接口就拥有了基本的数据库操作方法
public interface CustomerMapper extends JpaSpecificationExecutor<Customer>,JpaRepository<Customer,Long> {
//方法命名规范查询,findBy+字段名表示通过该字段查询
public Customer findByCustName(String name);
//Like表示通过CustName模糊查询,并且查询指定的地址
public List<Customer> findByCustNameLikeAndCustAddress(String custName,String address);
//自定义语句chaxun ?后面是参数的位置
@Query("from Customer where custName = ?1 and id =?2")
public Customer findNameAndId(String name,Long id);
//自定义语句chaxun
@Query("from Customer where custName = ?2 and id =?1")
public Customer findIdAndName(Long id,String name);
//自定义语句chaxun
@Query("update Customer set custName=?2 where custId = ?1")
@Modifying //表示此方法不是查询
public void updateIdByName(Long id,String name);
//自定义sql查询
@Query(value = "select * from cst_customer where cust_name = ?",nativeQuery = true)
public List<Object[]> findName(String name);
}
创建测试类
import com.baidu.dao.CustomerMapper;
import com.baidu.pojo.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.criteria.*;
import java.util.List;
import java.util.Set;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class springDateTest {
@Autowired
private CustomerMapper customerMapper;
@Test
public void findAll(){
List<Customer> list = customerMapper.findAll();
for (Customer customer : list) {
System.out.println(customer);
}
}
@Test
@Transactional
public void findOne(){
//findone表示立即加载查询
Customer customer = customerMapper.findOne(2l);
System.out.println(customer);
//getOne表示延迟加载
Customer mapperOne = customerMapper.getOne(2l);
System.out.println(mapperOne);
}
@Test
public void insert(){
//当使用save方法时,如果有id就是更新,没有id就是保存
Customer customer = new Customer();
customer.setCustName("吉林");
customerMapper.save(customer);
}
@Test
public void update(){
Customer customer = new Customer();
customer.setCustId(2l);
customer.setCustAddress("内蒙古");
customerMapper.save(customer);
}
@Test
public void findByName(){
Customer customer = customerMapper.findByCustName("斗鱼");
System.out.println(customer);
}
@Test
public void findlike(){
List<Customer> list = customerMapper.findByCustNameLikeAndCustAddress("吉%", "北京");
for (Customer customer : list) {
System.out.println(customer);
}
}
@Test
public void findNameAndId(){
Customer customer = customerMapper.findNameAndId("龙珠", 4l);
System.out.println(customer);
}
@Test
public void findIdAndName(){
Customer customer = customerMapper.findIdAndName(4l, "龙珠");
System.out.println(customer);
}
@Test
@Transactional
@Rollback(value = false)
public void updateName(){
customerMapper.updateIdByName(4l, "霸天");
}
//条件查询
@Test
public void findOrder(){
Specification<Customer> tSpecification = new Specification<Customer>() {
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Path<Object> custName = root.get("custName");
Path<Object> custId = root.get("custId");
Predicate predicate = cb.equal(custName.as(String.class), "霸天");
Predicate predicate2 = cb.equal(custId.as(Long.class), 4l);
Predicate p = cb.and(predicate, predicate2);
return p;
}
};
List<Customer> list = customerMapper.findAll(tSpecification);
for (Customer customer : list) {
System.out.println(customer);
}
}
//分页查询
@Test
public void pageSplit(){
Specification<Customer> tSpecification = new Specification<Customer>() {
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Path<Object> custId = root.get("custId");
Predicate predicate = cb.greaterThanOrEqualTo(custId.as(Long.class), 2l);
return predicate;
}
};
Pageable pageable = new PageRequest(1,2);
Page<Customer> page = customerMapper.findAll(tSpecification, pageable);
long totalElements = page.getTotalElements();
int totalPages = page.getTotalPages();
System.out.println(totalElements);
System.out.println(totalPages);
List<Customer> list = page.getContent();
for (Customer customer : list) {
System.out.println(customer);
}
}
}