【问题标题】:Unable to get insert, update and delete to work with spring-data-jpa无法插入、更新和删除以使用 spring-data-jpa
【发布时间】:2019-05-25 19:44:53
【问题描述】:

我正在尝试创建一个 Web 服务来执行使用 Spring Boot 2 编写的基本 CRUD 操作。选择操作工作正常,但是插入、删除和更新操作没有效果,因为它们的查询没有生成和执行。

我查看了不同的示例,但无法找出任何问题。对我来说主要担心的是,插入、删除或更新操作甚至没有触发查询。

学生实体

@Entity
@Table(name = "student")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Student {

@Id
@NotNull
@Column(name = "id")
private int id;

@NotNull
@Column(name = "name")
private String name;

@Column(name = "course")
private String course;

public Student(int id, String name, String course) {
    this.id = id;
    this.name = name;
    this.course = course;
}

public Student(){}

public int getId() {
    return id;
}

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

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getCourse() {
    return course;
}

public void setCourse(String course) {
    this.course = course;
}

@Override
public String toString() {
    return "Student{ id=" + id + ", name='" + name + '\'' + ", course='" + course + '\'' + '}';
}
}

StudentDaoImpl

@Repository
@Transactional
public class StudentDaoImpl implements StudentDao {

@Autowired
private EntityManagerFactory entityManagerFactory;

@Override
public List<Student> fetchAllStudents() {
    Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
    CriteriaBuilder cb = session.getCriteriaBuilder();
    CriteriaQuery<Student> cq = cb.createQuery(Student.class);
    Root<Student> root = cq.from(Student.class);
    CriteriaQuery<Student> all = cq.select(root);
    List<Student> solution = session.createQuery(all).getResultList();
    session.close();
    return solution;
}

@Override
public Student deleteStudent(Integer id) {
    Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
    Student student = session.load(Student.class, id);
    if (student != null){
        session.delete(student);
        session.close();
    }
    return student;
}

@Override
public Student fetchForId(Integer id){
    Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
    Student student = session.load(Student.class, id);
    session.close();
    return student;
}

@Override
public Student insertStudent(Student student) {
    Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
    session.save(student);
    session.close();
    return student;
}

@Override
public Student updateStudent(Student student) {
    Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
    Student studentCheck = session.load(Student.class, student.getId());
    if (studentCheck != null) {
        session.saveOrUpdate(student);
        session.close();
    }
    return student;
}
}

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=

spring.jpa.database = MYSQL
spring.jpa.show-sql = true

spring.jpa.hibernate.ddl-auto = update
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

编辑

用 EntityManager(+ Persistent Context Annotation) 替换 EntityManagerFactory 对我有用。但是我仍然不明白为什么持久性对 EntityManager 有效。

【问题讨论】:

    标签: spring-mvc spring-boot spring-data-jpa crud


    【解决方案1】:

    如果不是很重要,您可以使用NativeQuery 及其executeUpdate API:

    String query = "insert into student values(1,?)";
    
    em.createNativeQuery(query)
       .setParameter(1, "Tom")
       .executeUpdate();
    

    【讨论】:

    • 切换到EntityManager后,问题得到解决。但是我不知道为什么。
    【解决方案2】:

    我想推荐这个仓库

    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.stereotype.Repository;
    
    
    @Repository
    public interface StudentRepository extends JpaRepository<Student, Integer> {
    
    }
    

    可能您必须将 Student 的 id 从 int 更改为 Integer。

    并且这个存储库有检索、更新、创建和删除的方法。

    假设你想在服务中使用这个存储库,你可以这样做:

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    @Service
    @Transactional(rollbackFor = Exception.class)
    public class StudentService {
    
        @Autowired
        private StudentRepository studentRepository;
    
        ......
    
    }
    

    【讨论】:

    • 我想实现自己的存储库,而不是使用内置的。但是,这也有效,但不是我想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 2018-01-13
    • 1970-01-01
    • 2016-07-21
    • 2019-12-22
    • 1970-01-01
    • 2021-03-15
    相关资源
    最近更新 更多