Spring Data JPA动态查询 maven项目简单例子

项目结构如下:

Spring Data JPA动态查询 maven项目简单例子_第1张图片


pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>cn.db</groupId>
	<artifactId>psql</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>

	<name>psql Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<dependencies>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.10</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.0</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.5</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-jpa</artifactId>
			<version>1.6.1.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
			<version>1.1.4.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-resources-plugin</artifactId>
			<version>2.6</version>
		</dependency>

	</dependencies>

	<repositories>
		<repository>
			<id>spring-milestones</id>
			<url>http://repo.spring.io/libs-milestone</url>
		</repository>
	</repositories>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>


persistence.xml

<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
	version="2.0">
	<persistence-unit name="SimplePU" transaction-type="RESOURCE_LOCAL">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>

		<properties>
			<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
			<property name="hibernate.connection.url" value="jdbc:mysql://127.0.0.1:3306/db_cloud" />
			<property name="hibernate.connection.username" value="root" />
			<property name="hibernate.connection.password" value="root" />
			<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
			<property name="hibernate.show_sql" value="true" />
			<property name="hibernate.format_sql" value="true" />
			<property name="hibernate.use_sql_comments" value="false" />
			<property name="hibernate.hbm2ddl.auto" value="update" />
		</properties>
	</persistence-unit>
</persistence> 


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:p="http://www.springframework.org/schema/p"
	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/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
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context.xsd">

	<bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName">
			<value>com.mysql.jdbc.Driver</value>
		</property>
		<property name="url">
			<value>jdbc:mysql://127.0.0.1:3306/db_cloud</value>
		</property>
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>

	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>

	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>

	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
	</bean>

	<jpa:repositories base-package="cn.db.psql"
		entity-manager-factory-ref="entityManagerFactory"
		transaction-manager-ref="transactionManager" />

</beans>  


Person.java

package cn.db.psql;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "ts_person") 
public class Person {
	
	@Column
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Integer userid;
	
	@Column
	private String username;
	
	@Column
	private String stype;
	
	@Column
	private Integer city_id;

	public Integer getUserid() {
		return userid;
	}

	public void setUserid(Integer userid) {
		this.userid = userid;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getStype() {
		return stype;
	}

	public void setStype(String stype) {
		this.stype = stype;
	}

	public Integer getCity_id() {
		return city_id;
	}

	public void setCity_id(Integer city_id) {
		this.city_id = city_id;
	}
	
	public String toString()
	{
		return "[userid="+userid+",username="+username+",stype="+stype+",city_id="+city_id+"]";
	}
}

PersonJpaSpecificationExecutor.java

package cn.db.psql;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

/**
 * 复杂条件的查询
 */
@Repository("personJpaSpecificationExecutor")
public interface PersonJpaSpecificationExecutor extends JpaRepository<Person, Long>, JpaSpecificationExecutor<Person> 
{
	Page<Person> findAll(Specification<Person> spec, Pageable pageable);  //分页按条件查询  
	
	List<Person> findAll(Specification<Person> spec);
}

PersonRepository.java

package cn.db.psql;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

/**
 * 简单的查询
 */
@Repository("personRepository")
public interface PersonRepository extends JpaRepository<Person, Long> 
{
	@Query("select a from Person a where a.userid = :userid")
	public Person findByUserid(@Param("userid")Integer userid);
}


PersonSpecification.java

package cn.db.psql;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;

public class PersonSpecification implements Specification<Person>
{
	private String _username;
	private String _stype;
	private Integer _cityId;
	
	public PersonSpecification(String username, String stype, Integer cityId)
	{
		this._username = username;
		this._stype = stype;
		this._cityId = cityId;
	}
	
	public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query,CriteriaBuilder cb) 
	{
		
		Path<String> username = root.get("username");
		
		Path<String> stype = root.get("stype");
		Path<Integer> city_id = root.get("city_id");
		
		List<Predicate> list = new ArrayList<Predicate>(); 
		
		Predicate pa = cb.equal(username, _username);
		Predicate pb = cb.equal(stype, _stype);
		Predicate pc = cb.equal(city_id, _cityId);
		
		if(_username != null)
		{
			list.add(pa);
		}
		if(_stype != null)
		{
			list.add(pb);
		}
		if(_cityId != null)
		{
			list.add(pc);
		}
		
		Predicate[] parray = new Predicate[list.size()];
		
		return cb.and(list.toArray(parray));
	}

	public String get_username() {
		return _username;
	}

	public void set_username(String _username) {
		this._username = _username;
	}

	public String get_stype() {
		return _stype;
	}

	public void set_stype(String _stype) {
		this._stype = _stype;
	}

	public Integer get_cityId() {
		return _cityId;
	}

	public void set_cityId(Integer _cityId) {
		this._cityId = _cityId;
	}
}


Client.java

package cn.db.psql;

import java.util.List;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Client {
	
	public static void find() throws Exception
	{
		ClassPathXmlApplicationContext ctx = 
				new ClassPathXmlApplicationContext("applicationContext.xml"); 
		
		try
		{
			PersonJpaSpecificationExecutor ur = (PersonJpaSpecificationExecutor)ctx.getBean("personJpaSpecificationExecutor");
			
			PersonSpecification us = new PersonSpecification(null,"1",1);
			
			List<Person> plist = ur.findAll(us);
			
			System.out.println("==============================================");
			
			for(Person p : plist)
			{
				System.out.println(p);
			}
			
			System.out.println("==============================================");
			
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		
		ctx.close();
	}
	
	public static void main(String[] args) throws Exception
	{
		find();
	}
}




你可能感兴趣的:(Spring Data JPA动态查询 maven项目简单例子)