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 + '\'' +
                '}';
    }
}
相关推荐
confiself14 分钟前
大模型系列——LLAMA-O1 复刻代码解读
java·开发语言
Wlq041519 分钟前
J2EE平台
java·java-ee
小码的头发丝、21 分钟前
Django中ListView 和 DetailView类的区别
数据库·python·django
XiaoLeisj25 分钟前
【JavaEE初阶 — 多线程】Thread类的方法&线程生命周期
java·开发语言·java-ee
Karoku06631 分钟前
【企业级分布式系统】Zabbix监控系统与部署安装
运维·服务器·数据库·redis·mysql·zabbix
豪宇刘40 分钟前
SpringBoot+Shiro权限管理
java·spring boot·spring
Elaine20239144 分钟前
02多线程基础知识
java·多线程
gorgor在码农1 小时前
Redis 热key总结
java·redis·热key
周全全1 小时前
MySQL报错解决:The user specified as a definer (‘root‘@‘%‘) does not exist
android·数据库·mysql
白云如幻1 小时前
MySQL的分组函数
数据库·mysql