Respository:最顶层的接口也是标志接口,目的是为了统一所有Repository的类型,且能让组件扫描的时候自动识别。
准备工作
导入JAR包:
别忘了导入Junit测试包,否则后面没法单元测试
编写Spring和数据库配置文件
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:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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-4.3.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
>
<!--开启JPA命名空间 -->
<!--读取数据库外置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--配置数据源链接 -->
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="driverClass" value="${jdbc.driver.class}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置EntityManagerFactory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!--配置数据库类型 -->
<property name="database" value="MYSQL"/>
<!--开启正向工程 -->
<property name="generateDdl" value="true"/>
<!--显示SQL的语句 -->
<property name="showSql" value="true"/>
</bean>
</property>
<!--设置HBM.XML的POJO映射 -->
<property name="packagesToScan">
<list>
<value>com.OVA.pojo</value>
</list>
</property>
</bean>
<!--开启事务管理 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!--开启事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--开启Spring的注解扫描 -->
<context:component-scan base-package="com.OVA"/>
<!--Spring Data JPA配置 -->
<!--base-package扫描dao持久层接口所在的包 -->
<jpa:repositories base-package="com.OVA.dao"/>
</beans>
jdbc.properties
jdbc.url=jdbc:mysql:///springboot
jdbc.driver.class=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=666888
代码编写
1. 创建POJO对象实现序列化
package com.OVA.pojo;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@SuppressWarnings("serial")
@Entity
@Table(name = "users")
public class Users implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)//设置主键自增
@Column(name="userid")
private Integer userid;
@Column(name="username")
private String username;
@Column(name="userage")
private Integer userage;
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 Integer getUserage() {
return userage;
}
public void setUserage(Integer userage) {
this.userage = userage;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((userage == null) ? 0 : userage.hashCode());
result = prime * result + ((userid == null) ? 0 : userid.hashCode());
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Users other = (Users) obj;
if (userage == null) {
if (other.userage != null)
return false;
} else if (!userage.equals(other.userage))
return false;
if (userid == null) {
if (other.userid != null)
return false;
} else if (!userid.equals(other.userid))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
@Override
public String toString() {
return "Users [userid=" + userid + ", username=" + username + ", userage=" + userage + "]";
}
}
2. 创建POJO对象操作接口
package com.OVA.dao;
import java.util.List;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import com.OVA.pojo.Users;
/**
* @author OVA_Wom Repository 参数一:操作对象的类型;参数二:对象主键的类型
**/
public interface UserDao extends Repository<Users, Integer> {
// 方式一:使用Repository方法命名规则实现查询
List<Users> findByUsername(String string);
List<Users> findByUsernameLike(String string);
List<Users> findByUsernameAndUserageGreaterThanEqual(String string, Integer userage);
List<Users> findByUsernameLikeAndUserageGreaterThanEqual(String string, Integer userage);
List<Users> findByUserageBetween(Integer userage1, Integer userage2);
List<Users> findByUsernameOrderByUserageDesc(String string);
// 方式二:通过@Quey注解JPQL语言进行查询
// 参数顺序是从左至右一次绑定
@Query(value = "from Users where username=?")
List<Users> queryByUsername(String username);
@Query("from Users where username like ?")
List<Users> QueryUsernameLike(String username);
@Query("from Users where username like ? and userage>?")
List<Users> QueryUserage(String username, Integer userage);
// 使用@Query注解SQL语句查询
// nativeQuery=true设置使用原生的SQL语句进行查询
@Query(value = "select * from users where username=?", nativeQuery = true)
List<Users> queryByUsernameSQL(String username);
@Query(value = "select * from users where username like ?", nativeQuery = true)
List<Users> QueryUsernameLikeSQL(String username);
@Query(value = "select * from users where username like ? and userage>?", nativeQuery = true)
List<Users> QueryUserageSQL(String username, Integer userage);
// @Query注解JPQL实现更新
@Query("update Users set userage=? where userid=?")
@Modifying
int updateUserageByIdJPQL(Integer userage, Integer id);
// @Query注解SQL实现更新
@Query(value="update users set userage=? where userid=?",nativeQuery=true)
@Modifying
int updateUserageByIdSQL(Integer userage, Integer id);
}
3. 创建测试类进行测试
package test;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
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 com.OVA.dao.UserDao;
import com.OVA.pojo.Users;
/**
* @author OVA_Wom Repository测试接口
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RepositoryTest {
@Autowired
private UserDao userdao;
// 用户名作为检索条件
@Test
@Transactional
@Rollback(false)
public void testName() {
/*
* 判断相等的查询条件有三种表示方式 什么也不写默认 可以使用is 可以使用equal
*/
List<Users> findByUsernameIs = userdao.findByUsername("张三");
for (Users u : findByUsernameIs) {
System.out.println(u);
}
}
// 根据用户的姓名做LIKE处理
// Like条件关键字
@Test
@Transactional
@Rollback(false)
public void testLike() {
List<Users> findByUsernameLike = userdao.findByUsernameLike("张%");
for (Users u : findByUsernameLike) {
System.out.println(u);
}
}
// 多条件查询
@Test
@Transactional
@Rollback(false)
public void testNameAndAge() {
List<Users> findByUsernameAndUserageGreaterThanEqual = userdao.findByUsernameAndUserageGreaterThanEqual("张三",
12);
for (Users u : findByUsernameAndUserageGreaterThanEqual) {
System.out.println(u);
}
}
// 多条件查询,姓名以张开头,年龄大于11的人
@Test
@Transactional
@Rollback(false)
public void testNameLikeAndAge() {
List<Users> findByUsernameLikeAndUserageGreaterThanEqual = userdao
.findByUsernameLikeAndUserageGreaterThanEqual("张%", 22);
for (Users users : findByUsernameLikeAndUserageGreaterThanEqual) {
System.out.println(users);
}
}
// 查询用户按年龄区间
@Test
@Transactional
@Rollback(false)
public void testUserageBetween() {
List<Users> findByUserageBetween = userdao.findByUserageBetween(11, 50);
for (Users users : findByUserageBetween) {
System.out.println(users);
}
}
// 将下沟通姓名的用户按照年龄大小降序
@Test
@Transactional
@Rollback(false)
public void testUserageOrder() {
List<Users> findByUsernameOrderByUserageDesc = userdao.findByUsernameOrderByUserageDesc("张三");
for (Users users : findByUsernameOrderByUserageDesc) {
System.out.println(users);
}
}
// 使用@Queryd注解JPQL方式查询用户
@Test
@Transactional
@Rollback(false)
public void testQueryUsername() {
List<Users> queryByUsername = userdao.queryByUsername("张三");
for (Users users : queryByUsername) {
System.out.println(users);
}
}
// 使用@Queryd注解JPQL方式进行模糊查询
@Test
@Transactional
@Rollback(false)
public void testQueryUsernameLike() {
List<Users> queryUsernameLike = userdao.QueryUsernameLike("张%");
for (Users users : queryUsernameLike) {
System.out.println(users);
}
}
// 使用@Queryd注解JPQL方式进行多条件查询
@Test
@Transactional
@Rollback(false)
public void testQueryUserage() {
List<Users> queryUserage = userdao.QueryUserage("张%", 20);
for (Users users : queryUserage) {
System.out.println(users);
}
}
// 使用@Queryd注解SQL方式查询用户
@Test
@Transactional
@Rollback(false)
public void testQueryUsernameSQL() {
List<Users> queryByUsernameSQL = userdao.queryByUsernameSQL("张三");
for (Users users : queryByUsernameSQL) {
System.out.println(users);
}
}
// 使用@Queryd注解SQL方式进行模糊查询
@Test
@Transactional
@Rollback(false)
public void testQueryUsernameLikeSQL() {
List<Users> queryUsernameLikeSQL = userdao.QueryUsernameLikeSQL("张%");
for (Users users : queryUsernameLikeSQL) {
System.out.println(users);
}
}
// 使用@Queryd注解SQL方式进行多条件查询
@Test
@Transactional
@Rollback(false)
public void testQueryUserageSQL() {
List<Users> queryUserageSQL = userdao.QueryUserageSQL("张%", 20);
for (Users users : queryUserageSQL) {
System.out.println(users);
}
}
// 使用@Queryd注解JPQL方式进行数据更新
@Test
@Transactional
@Rollback(false)
public void testUpdateJPQL() {
System.out.println(userdao.updateUserageByIdJPQL(111, 14));
}
// 使用@Queryd注解SQL方式进行数据更新
@Test
@Transactional
@Rollback(false)
public void testUpdateSQL() {
System.out.println(userdao.updateUserageByIdSQL(11, 14));
}
}
代码已经加详细的注释,以上就是Respository接口的基本内容,不足之处还请大神指正。