SpringDataJPA基础增删改查

添加:save(对象)

删除:delete(主键或者带有主键的对象)

修改:save(对象)

对象中没有id,执行添加操作

对象中有id

id不存在:执行添加

id存在:

其余数据与数据库中一致,只发送查询

其余数据与数据库中不一致,发送更新语句

查询

查询某一个findOne(主键) 及时加载

查询某一个getOne(主键) 懒加载

使用过程中会报no session问题,需要追加@Transactional

查询某一个findOne(动态参数)

@Test
public void find() {
    Specification<User> spec = new Specification<User>() {

        @Override
        public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {

            Path<Object> username = root.get("username");
            Path<Object> id = root.get("id");
            Path<Object> age = root.get("age");

            Predicate p1 = cb.equal(username, 1111);
            Predicate p2 = cb.equal(id, 1);
            Predicate p3 = cb.equal(age, 18);
            Predicate[] ps = new Predicate[3];
            ps[0] = p1;
            ps[1] = p2;
            ps[2] = p3;
            Predicate predicate = cb.and(ps);
            return predicate;
        }
    };
    User user = userDao.findOne(spec);
    System.out.println(user);
}

查询所有findAll()

查询所有并排序findAll(sort)

Sort sort = new Sort(Sort.Direction.DESC,"id");
List<User> userList = userdao.findAll(sort);

查询所有并分页findAll(pageable)

Pageable pageable = new PageRequest(0,5);
Page<User> page = userdao.findAll(pageable);

动态查询所有并分页findAll(动态参数,pageable)

参考查询某一个findOne(动态参数)

动态查询所有并排序findAll(动态参数,sort)

参考查询某一个findOne(动态参数)

通过JPQL语句个性化查询

//通过用户名查询
@Query("from User where username=?1")
User test01(String username);
//通过用户名、密码登录
@Query("from User where username=?1 and password = ?2")
User login(String username,String password);
//通过id搜索用户名
@Query("select username from User where id=?1")
User test02(int id);

通过SQL个性化查询

@Query(value = "select username from User where id=?1",nativeQuery = true)
User test03(int id);

通过个性化方法名称査询 find+By+属性名称+And+....

User findByUsernameAndPassword(string username,string password);
List<User> findTop5ByUsername(string username);
User findByUsernameLike(string username):

关联关系

一对多

从多查一:默认及时加载,发送一条 sql 语句

从一査多:默认懒加载,发送多条sql语句,报错

解决方式一:追加@Transactional

解决方式二:开启及时加载

package com.xszx.beans;

import javax.persistence.*;

@Entity
@Table(name = "t_user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String username;
    private String password;
    private int age;
    /**
    * @ManyToOne 多对一
     * 属性targetEntity:对方的字节码
    * @JoinColumn 加入列名
     * 属性name:列的名称
     * 属性referencedColumnName:对方表的主键列名
    */

    @ManyToOne(targetEntity = Group.class)
    @JoinColumn(name = "gid",referencedColumnName = "gid")
    private Group group;

    public Group getGroup() {
        return group;
    }

    public void setGroup(Group group) {
        this.group = group;
    }

    public User() {
    }

    public User(int id, String username, String password, int age) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.age = age;
    }

    public User(int age, String password, String username) {
        this.age = age;
        this.password = password;
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                '}';
    }
}

package com.xszx.beans;


import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "t_group")
public class Group {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int gid;
    private String gname;
    /**
     *  @OneToMany 一对多
     *  属性targetEntity:对方字节码
     *  属性mappedBy:对方实体类中,对方属性名,关系由对方维护
     *  属性fetch:配置懒加载与及时加载
     *  */
    @OneToMany(targetEntity = User.class,mappedBy = "group",fetch = FetchType.EAGER)
    private List<User> users;

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

    public Group() {
    }

    public Group(int gid, String gname) {
        this.gid = gid;
        this.gname = gname;
    }

    public int getGid() {
        return gid;
    }

    public void setGid(int gid) {
        this.gid = gid;
    }

    public String getGname() {
        return gname;
    }

    public void setGname(String gname) {
        this.gname = gname;
    }

    @Override
    public String toString() {
        return "Group{" +
                "gid=" + gid +
                ", gname='" + gname + '\'' +
                '}';
    }
}

多对多

package com.xszx.beans;

import javax.persistence.*;
import java.util.List;

@Entity
@Table(name = "t_student")
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int sid;
    private String sname;

    /**
     * @ManyToMany 多对多
     * 属性targetEntity:对方的字节码
     * @joinTable 加入中间表
     * 属性name:中间表名
     * 属性joinColumns:本类在中间表的字段
     * 属性inverseJoinColumns:对方在中间表的字段
     */

    @ManyToMany(targetEntity = Teacher.class)
    @JoinTable(name = "t_stu_tea",
    joinColumns = {@JoinColumn(name = "sid",referencedColumnName = "sid")},
    inverseJoinColumns = {@JoinColumn(name = "tid",referencedColumnName = "tid")})
    private List<Teacher> teachers;

    public List<Teacher> getTeachers() {
        return teachers;
    }

    public void setTeachers(List<Teacher> teachers) {
        this.teachers = teachers;
    }

    public Student() {
    }

    public Student(int sid, String sname) {
        this.sid = sid;
        this.sname = sname;
    }

    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", sname='" + sname + '\'' +
                '}';
    }
}

package com.xszx.beans;

import javax.persistence.*;
import java.util.List;

@Entity
@Table(name = "t_teacher")
public class Teacher {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int tid;
    private String tname;
    @ManyToMany(targetEntity = Student.class,mappedBy = "teachers")
    private List<Student> students;

    public Teacher() {
    }

    public Teacher(int tid, String tname) {
        this.tid = tid;
        this.tname = tname;
    }
    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }
    public int getTid() {
        return tid;
    }

    public void setTid(int tid) {
        this.tid = tid;
    }

    public String getTname() {
        return tname;
    }

    public void setTname(String tname) {
        this.tname = tname;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "tid=" + tid +
                ", tname='" + tname + '\'' +
                '}';
    }
}
相关推荐
Q_19284999065 分钟前
基于Spring Boot的摄影器材租赁回收系统
java·spring boot·后端
Code_流苏8 分钟前
VSCode搭建Java开发环境 2024保姆级安装教程(Java环境搭建+VSCode安装+运行测试+背景图设置)
java·ide·vscode·搭建·java开发环境
Mr.131 小时前
数据库的三范式是什么?
数据库
禁默1 小时前
深入浅出:AWT的基本组件及其应用
java·开发语言·界面编程
Cachel wood1 小时前
python round四舍五入和decimal库精确四舍五入
java·linux·前端·数据库·vue.js·python·前端框架
Code哈哈笑1 小时前
【Java 学习】深度剖析Java多态:从向上转型到向下转型,解锁动态绑定的奥秘,让代码更优雅灵活
java·开发语言·学习
gb42152871 小时前
springboot中Jackson库和jsonpath库的区别和联系。
java·spring boot·后端
程序猿进阶1 小时前
深入解析 Spring WebFlux:原理与应用
java·开发语言·后端·spring·面试·架构·springboot
Python之栈1 小时前
【无标题】
数据库·python·mysql