什么是SpringData?
Spring Data 是一个用于简化数据访问和持久化的开源框架,它为 Java 开发人员提供了一种统一且简单的方式来与各种数据库进行交互。它是 Spring 框架下的一个子项目,旨在提供统一的 API 和抽象层,使得开发人员可以更轻松地使用不同种类的数据存储技术,包括关系型数据库(如MySQL、PostgreSQL)、NoSQL 数据库(如MongoDB、Redis)等。
Spring Data 提供了一组通用的功能和特性,包括:
1. 数据库访问抽象:统一了不同类型数据库的访问方式,无需编写过多的重复代码。
2. CRUD 操作支持:通过继承或注解方式,开发人员可以自动生成常见的增删改查方法,无需手动实现。
3. 查询方法自动生成:基于方法命名规则或使用注解,可以根据方法签名自动生成查询语句。
4. 分页和排序支持:内置对分页和排序的支持,使得处理大量数据更加便捷。
5. 声明式事务管理:提供了声明式的事务管理机制,简化了事务的使用和配置。
6. 缓存支持:集成了缓存框架,可以方便地添加缓存功能,提升应用性能。
7. 异步操作支持:支持异步处理,使得请求响应更为高效。
8. 多数据源支持:可以同时连接和操作多个不同类型的数据库。
9. 扩展机制:提供了丰富的扩展点和接口,以便根据实际需要进行定制和扩展。Spring Data 提供了一系列模块,以适应不同的数据存储技术,例如 Spring Data JPA、Spring Data MongoDB、Spring Data Redis 等。每个模块都基于相应的数据访问技术,并在其之上提供了统一的 API 和特性,简化了开发人员对不同数据库的使用和切换。
总而言之,Spring Data 提供了一个强大而灵活的数据访问框架,帮助开发人员更加高效地进行数据访问和持久化操作,并且降低了与不同数据存储技术集成的复杂性。
1.创建两个实体类
注解 | |
@Entity | 实体 |
@Table(name="t_menus") | 数据库的表名字 |
@Id | 是设置下面的变量为唯一标识符 |
@GeneratedValue(strategy=GenerationType.IDENTITY) | 用于指定主键的生成策略。它通常与 @Id 注解一起使用 |
@Column(name="mId") 它可以用来自定义该属性或方法在数据库表中对应的列的信息
1.创建两个实体类 两个类都需要用集合来存储。
package com.springData.bean;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
//菜单类,一个菜单可以对应多个角色
@Entity //实体
@Table(name="t_menus") //数据库的表名字
public class Menus {
@Id //用于标记一个字段或方法作为对象的唯一标识符。通常情况下
//@Id 注解标记了 id 字段,表示它是 User 对象在数据库中的唯一标识符
@GeneratedValue(strategy=GenerationType.IDENTITY)
//用于指定主键的生成策略。它通常与 @Id 注解一起使用
//它可以用来自定义该属性或方法在数据库表中对应的列的信息
@Column(name="mId")
private Integer mId;
@Column(name="mName")
private String mName;
@ManyToMany(mappedBy="menusSet")
private Set<Roles> rolesSet = new HashSet<>();
public Set<Roles> getRolesSet() {
return rolesSet;
}
public void setmName(String mName) {
this.mName = mName;
}
public void setRolesSet(Set<Roles> rolesSet) {
this.rolesSet = rolesSet;
}
public Integer getmId() {
return mId;
}
public void setmId(Integer mId) {
this.mId = mId;
}
}
package com.springData.bean;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity //实体
@Table(name="t_roles") //数据库的表名字
public class Roles {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="rId")
private Integer rId;
@Column(name="rName")
private String rName;
public void setrName(String rName) {
this.rName = rName;
}
@ManyToMany(cascade=CascadeType.PERSIST,fetch=FetchType.EAGER)
//前半部分级联 后面及时匹配
//后半部分意思是加一个主键和一个外键
@JoinTable(name="roles_menus",joinColumns=@JoinColumn(name="rId"),inverseJoinColumns=@JoinColumn(name="mId"))
private Set<Menus> menusSet = new HashSet<>();
public Integer getrId() {
return rId;
}
public void setrId(Integer rId) {
this.rId = rId;
}
public Set<Menus> getMenusSet() {
return menusSet;
}
public void setMenusSet(Set<Menus> menusSet) {
this.menusSet = menusSet;
}
}
2.增加Dao层
package com.springData.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import com.springData.bean.Roles;
public interface RolesMapper extends JpaRepository<Roles, Integer>{
}
3.增加测试类
调用dao层有两种方法
package com.springData.test;
import java.util.HashSet;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.springData.bean.Menus;
import com.springData.bean.Roles;
import com.springData.dao.RolesMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:SpringData.xml")
public class Demo {
//拿到数据访问层对象,用于调用增删改查方法
@Autowired
private RolesMapper rolesMapper;
//增加,一个角色多个菜单
@Test
public void addInfo() {
//创建角色
Roles roles = new Roles();
roles.setrName("角色1");
//创建多个菜单
Menus menus = new Menus();
menus.setmName("菜单1");
Menus menus2 = new Menus();
menus2.setmName("菜单2");
Menus menus3 = new Menus();
menus3.setmName("菜单3");
//将角色添加到菜单中
menus.getRolesSet().add(roles);
menus2.getRolesSet().add(roles);
menus3.getRolesSet().add(roles);
//将菜单添加到角色中
roles.getMenusSet().add(menus);
roles.getMenusSet().add(menus2);
roles.getMenusSet().add(menus3);
rolesMapper.save(roles);
System.out.println("成功");
}
//增加 ,一个菜单多个角色
@Test
public void addInfo2() {
//创建一个菜单
Menus menus = new Menus();
menus.setmName("餐厅");
//创建多个角色
Roles roles = new Roles();
roles.setrName("泡馍");
Roles roles2 = new Roles();
roles2.setrName("油泼面");
Roles roles3 = new Roles();
roles3.setrName("饺子");
//将菜单添加到角色里
roles.getMenusSet().add(menus);
roles2.getMenusSet().add(menus);
roles3.getMenusSet().add(menus);
//将角色添加到菜单中
menus.getRolesSet().add(roles);
menus.getRolesSet().add(roles2);
menus.getRolesSet().add(roles3);
HashSet<Roles> hashSet = new HashSet<>();
hashSet.add(roles);
hashSet.add(roles2);
hashSet.add(roles3);
rolesMapper.save(hashSet);
System.out.println("好了");
}
}
4.数据库资源文档
注意3308后面一定要跟的是数据库的表名。
jdbc.url=jdbc:mysql://localhost:3308/manytomany
jdbc.driver.class=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=1234
5.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: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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 1.扫包 -->
<context:component-scan base-package="com.springData"></context:component-scan>
<!-- 2.加载属性文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 3.创建连接数据库的对象 -->
<bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">
<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>
<!-- 4.创建的SpringDataJpa对象,用于提供增删改查方法 -->
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="dataSource" ref="dataSource"/>
<property name="JpaVendorAdapter">
<bean 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>
<property name="packagesToScan">
<list>
<value>com.springData.bean</value>
</list>
</property>
</bean>
<!-- 5.创建事务对象,用于协助增删改 -->
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- 6.配置事务驱动 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 7.将含有“JPA接口或类的所在包”,配置在此处,用于关联增删改查方法 -->
<jpa:repositories base-package="com.springData.dao"/>
</beans>