hibernate/ Spring JPA的save方法不会在数据库中保存一条记录

时间:2022-09-11 16:26:49

I've seen quit a lot of posts about this topic, but I can't seem to fix it. The problem that I am facing is that I can't seem to insert data in my database (postgres).

我见过很多关于这个话题的帖子,但是我似乎无法修复它。我所面临的问题是,我似乎无法在我的数据库中插入数据(postgres)。

Table Types

表类型

hibernate/ Spring JPA的save方法不会在数据库中保存一条记录

I want to add another row (i.e. YouTube)

我想再加一行(比如YouTube)

Type -- model

类型——模型

@Entity
@Table(name = "types")
public class Type {

    // region: parameters
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "name", unique = true)
    private String name;
    // endregion: parameters

    // region: relationships
    @JsonIgnore
    @ManyToMany(mappedBy = "types")
    private Set<License> licenses;
    // endregion: relationships

    // region: constructors
    public Type() {
    }

    public Type(String name, Set<License> licenses) {
        this.name = name;
        this.licenses = licenses;
    }
    // endregion: constructors

    // region: getters & setters
    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Set<License> getLicenses() {
        return licenses;
    }

    public void setLicenses(Set<License> licenses) {
        this.licenses = licenses;
    }
    // endregion: getters & setters
}

TypeServiceImpl -- service

TypeServiceImpl——服务

@Service
public class TypeServiceImpl implements TypeService {
    private final TypeRepository typeRepository;

    @Autowired
    public TypeServiceImpl(TypeRepository typeRepository) {
        this.typeRepository = typeRepository;
    }

    public Iterable<Type> list() {
        return typeRepository.findAll();
    }

    public boolean existByName(String name) {
        return typeRepository.existByName(name);
    }

    @Transactional
    public Type save(Type type) {
        return typeRepository.save(type);
    }
}

the implements TypeService is currently just an empty interface.

目前,实现的TypeService只是一个空接口。

TypeRepository -- dao

TypeRepository——刀

@Repository
public interface TypeRepository extends CrudRepository<Type, Integer> {
    @Query("SELECT CASE WHEN COUNT (t) > 0 THEN true ELSE false END FROM Type t WHERE t.name = :name")
    boolean existByName(@Param("name") String name);
}

TypeController -- restcontroller

TypeController——restcontroller

@RestController
public class TypeController {
    private final TypeServiceImpl typeService;

    @Autowired
    public TypeController(TypeServiceImpl typeService) {
        this.typeService = typeService;
    }

    @RequestMapping(method = RequestMethod.GET, path = "/types")
    public Iterable<Type> getAllTypes() {
        return typeService.list();
    }

    @RequestMapping(method = RequestMethod.POST, path = "/types")
    public Type createRole(@RequestBody Type type) {
        return typeService.save(type);
    }
}

Whenever I do a post to /types with a Json body

每当我用Json体做post /type时

{
    "name": "Youtube"
}

it returns:

它返回:

{
    "id": null,
    "name": "Youtube"
}

When I look back at my table it isn't inserted.

当我回头看表时,它没有被插入。

Logs after posting to /types

张贴到/类型后的日志

19:00:21.619 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'dispatcher' processing POST request for [/types]
19:00:21.625 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Looking up handler method for path /types
19:00:21.634 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Returning handler method [public com.hitmax.server.mvc.model.Type com.hitmax.server.mvc.controller.TypeController.createRole(com.hitmax.server.mvc.model.Type)]
19:00:21.634 [http-nio-8080-exec-1] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'typeController'
19:00:21.926 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor - Read [class com.hitmax.server.mvc.model.Type] as "application/json" with [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@1206e027]
19:00:21.984 [http-nio-8080-exec-1] DEBUG org.springframework.core.annotation.AnnotationUtils - Failed to meta-introspect annotation [interface org.springframework.web.bind.annotation.RequestBody]: java.lang.IllegalArgumentException: Annotation must not be null
19:00:22.006 [http-nio-8080-exec-1] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'transactionManager'
19:00:22.021 [http-nio-8080-exec-1] DEBUG org.springframework.orm.hibernate5.HibernateTransactionManager - Creating new transaction with name [com.hitmax.server.mvc.dao.service.type.TypeServiceImpl.save]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
19:00:22.021 [http-nio-8080-exec-1] DEBUG org.hibernate.stat.internal.StatisticsInitiator - Statistics initialized [enabled=false]
19:00:22.022 [http-nio-8080-exec-1] DEBUG org.springframework.orm.hibernate5.HibernateTransactionManager - Opened new Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for Hibernate transaction
19:00:22.033 [http-nio-8080-exec-1] DEBUG org.springframework.orm.hibernate5.HibernateTransactionManager - Preparing JDBC Connection of Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
19:00:22.033 [http-nio-8080-exec-1] DEBUG org.springframework.jdbc.datasource.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:postgresql://localhost:5432/hitmaxServer]
19:00:22.098 [http-nio-8080-exec-1] DEBUG org.hibernate.engine.transaction.internal.TransactionImpl - begin
19:00:22.103 [http-nio-8080-exec-1] DEBUG org.springframework.orm.hibernate5.HibernateTransactionManager - Exposing Hibernate transaction as JDBC transaction [org.postgresql.jdbc4.Jdbc4Connection@594b5ba9]
19:00:22.139 [http-nio-8080-exec-1] DEBUG org.springframework.data.repository.core.support.TransactionalRepositoryProxyPostProcessor$CustomAnnotationTransactionAttributeSource - Adding transactional method 'save' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
19:00:22.143 [http-nio-8080-exec-1] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'transactionManager'
19:00:22.143 [http-nio-8080-exec-1] DEBUG org.springframework.orm.hibernate5.HibernateTransactionManager - Found thread-bound Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] for Hibernate transaction
19:00:22.143 [http-nio-8080-exec-1] DEBUG org.springframework.orm.hibernate5.HibernateTransactionManager - Participating in existing transaction
19:00:22.165 [http-nio-8080-exec-1] DEBUG org.springframework.orm.jpa.EntityManagerFactoryUtils - Opening JPA EntityManager
19:00:22.166 [http-nio-8080-exec-1] DEBUG org.springframework.orm.jpa.EntityManagerFactoryUtils - Registering transaction synchronization for JPA EntityManager
19:00:22.273 [http-nio-8080-exec-1] DEBUG org.springframework.orm.jpa.EntityManagerFactoryUtils - Closing JPA EntityManager
19:00:22.277 [http-nio-8080-exec-1] DEBUG org.springframework.orm.hibernate5.HibernateTransactionManager - Initiating transaction commit
19:00:22.277 [http-nio-8080-exec-1] DEBUG org.springframework.orm.hibernate5.HibernateTransactionManager - Committing Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
19:00:22.277 [http-nio-8080-exec-1] DEBUG org.hibernate.engine.transaction.internal.TransactionImpl - committing
19:00:22.278 [http-nio-8080-exec-1] DEBUG org.springframework.orm.hibernate5.HibernateTransactionManager - Closing Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])] after transaction
19:00:22.396 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor - Written [com.hitmax.server.mvc.model.Type@268e7743] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@1206e027]
19:00:22.397 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'dispatcher': assuming HandlerAdapter completed request handling
19:00:22.397 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Successfully completed request

Any help would be appreciated.

如有任何帮助,我们将不胜感激。

<>

< >

2 个解决方案

#1


0  

Try to work with a diferent id generation strategy other than GenerationType.IDENTITY. Do a simple test using GenerationType.AUTO a see what happens.

尝试使用除generation type . identity之外的另一种id生成策略。使用GenerationType做一个简单的测试。自动a看看会发生什么。

#2


0  

In the process of posting this question I found the answer. It was really hard to find, but I did it. I still posted this question so people that have this problem might get something out of this.

在发布这个问题的过程中,我找到了答案。真的很难找到,但我做到了。我还是贴了这个问题,所以有这个问题的人可能会从中得到一些东西。

The problem

这个问题

Inside my JpaConfiguration file I was using the HibernateTransactionManager manager:

在我的JpaConfiguration文件中,我使用了HibernateTransactionManager管理器:

@Bean
public HibernateTransactionManager transactionManager(final SessionFactory sessionFactory) {
    HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
    hibernateTransactionManager.setSessionFactory(sessionFactory);

    return hibernateTransactionManager;
}

I changed this to the JpaTransactionManager and that seemed to do the trick:

我把这个改成了JpaTransactionManager,这看起来很有用:

@Bean
public JpaTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) {
    JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
    jpaTransactionManager.setEntityManagerFactory(entityManagerFactory);

    return jpaTransactionManager;
}

#1


0  

Try to work with a diferent id generation strategy other than GenerationType.IDENTITY. Do a simple test using GenerationType.AUTO a see what happens.

尝试使用除generation type . identity之外的另一种id生成策略。使用GenerationType做一个简单的测试。自动a看看会发生什么。

#2


0  

In the process of posting this question I found the answer. It was really hard to find, but I did it. I still posted this question so people that have this problem might get something out of this.

在发布这个问题的过程中,我找到了答案。真的很难找到,但我做到了。我还是贴了这个问题,所以有这个问题的人可能会从中得到一些东西。

The problem

这个问题

Inside my JpaConfiguration file I was using the HibernateTransactionManager manager:

在我的JpaConfiguration文件中,我使用了HibernateTransactionManager管理器:

@Bean
public HibernateTransactionManager transactionManager(final SessionFactory sessionFactory) {
    HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
    hibernateTransactionManager.setSessionFactory(sessionFactory);

    return hibernateTransactionManager;
}

I changed this to the JpaTransactionManager and that seemed to do the trick:

我把这个改成了JpaTransactionManager,这看起来很有用:

@Bean
public JpaTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) {
    JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
    jpaTransactionManager.setEntityManagerFactory(entityManagerFactory);

    return jpaTransactionManager;
}