休眠异常:无法提交JPA事务;嵌套异常为javax.persistence.RollbackException:提交事务时出错

时间:2018-09-24 10:05:37

标签: java hibernate

我有一个实体类MailingList,源代码如下:

@Data
@Entity
@Table(name = AccountConstants.TABLE_NAME_MAILING_LIST, uniqueConstraints = @UniqueConstraint(columnNames = { "list_name" }))
@EntityListeners(MailingListListener.class)
public class MailingList extends AbstractBaseEntity implements Serializable, BasicEntity<Long> {
    public static final String MAILINGLIST_PROP_NAME = "list_name";
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "mail_list_generator")
    @SequenceGenerator(name = "mail_list_generator", sequenceName = "mail_list_seq", allocationSize = 1, initialValue = 1)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;

    @Column(name = "list_name", length = 50, nullable = false, updatable = true) 
    private String name;
}

您可以看到,上面的实体将侦听器添加到类MailingListListener,下面是MailingListListener的源代码

@Component
public class MailingListListener {
    @PrePersist
    public void onPrePersist(Object o) {

        try {
            if (o instanceof Timestampable) {
                Timestampable tso = (Timestampable) o;
                tso.setCreatedAt(new Date());
                tso.setActive(true);
                tso.setCreatedBy(getUserId());
             }
          } catch (Exception e) {
             LOGGER.error(e.getMessage(), e);
          }
     }

private void sendMailingList(MailingList mailingList) {

    try {
        MailingListVM vm = MailingListMapper.INSTANCE.toMailingListVM(mailingList);
        KafkaMessage kafkaMsg = KafkaUtil.saveKafkaMessage(vm, BaseConstants.TABLE_NAME_MAILING_LIST, "uaa");

        Map<String, Object> sendingData = new HashMap<>();
        if (mailingList.getActive() == null || mailingList.getActive() == false) {
            sendingData.put(BaseConstants.KAFKA_ACTION, BaseConstants.KAFKA_ACTION_DELETE);
        } else {
            sendingData.put(BaseConstants.KAFKA_ACTION, BaseConstants.KAFKA_ACTION_UPDATE);
        }

        sendingData.put(BaseConstants.TABLE_NAME, BaseConstants.TABLE_NAME_MAILING_LIST + "");

        sendingData.put(MailingList.PROP_ID, mailingList.getId().longValue() + "");
        sendingData.put(MailingList.MAILINGLIST_PROP_NAME, mailingList.getName());
        sendingData.put(MailingList.PROP_CREATED_AT, mailingList.getCreatedAt());
        sendingData.put(MailingList.PROP_UPDATED_AT, mailingList.getUpdatedAt());

        sendingData.put(KafkaMessage.SOURCE_SERVICE, KafkaMessage.UAA_SERVICE);
        sendingData.put(KafkaMessage.KAFKA_MESSAGE_ID, kafkaMsg.getId() != null ? kafkaMsg.getId() + "" : "-1");

        UpdatedUaaPublicProducerChannel updatedUaaPublicProducerChannel = ApplicationContextHolder
                .getBean(UpdatedUaaPublicProducerChannel.class);
        updatedUaaPublicProducerChannel.updateUaaPublic().send(MessageBuilder.withPayload(sendingData).build());
    } catch (Exception e) {
        LOGGER.info(e.getMessage(), e);
    }
}

    @PostPersist
    public void onPostPersist(Object o) {

        MailingList obj = (MailingList) o;
        send1MailingList(obj);
    }

}

您可以看到代码。每当我将新记录更新或插入到MailingList表中时,它将执行功能sendMailingList。该功能仅将一条记录保存到表kafka_message表中,并仅向kafka服务器发送一条消息。但是我不明白如果我注释此函数的2个第一行代码,那么我也可以运行

MailingListVM vm = MailingListMapper.INSTANCE.toMailingListVM(mailingList);

KafkaMessage kafkaMsg = KafkaUtil.saveKafkaMessage(vm, BaseConstants.TABLE_NAME_MAILING_LIST, "uaa");

函数KafkaUtil.saveKafkaMessage的内容如下

public final static KafkaMessage saveKafkaMessage(Object dept, String tableName, String source) {
    Session session = null;
    session = ApplicationContextHolder.getSessionFactory().openSession();

    try {
        KafkaMessage kafkaMessage = new KafkaMessage();
        kafkaMessage.setContents(KafkaUtil.writeValueAsString(dept));
        kafkaMessage.setTableName(tableName);
        if(source.equals("device")) {
            kafkaMessage.setDeviceServiceReceived(new Long(2));
        } else if(source.equals("facility")) {
            kafkaMessage.setFacilityServiceReceived(new Long(2));
        } else if(source.equals("archive")) {
            kafkaMessage.setArchiveServiceReceived(new Long(2));
        } else if(source.equals("uaa")) {
            kafkaMessage.setUaaServiceReceived(new Long(2));
        } else if(source.equals("monitoring")) {
            kafkaMessage.setMonitoringServiceReceived(new Long(2));
        } else if(source.equals("sale")) {
            kafkaMessage.setSaleServiceReceived(new Long(2));
        }
        session = ApplicationContextHolder.getSessionFactory().openSession();
                    Transaction transaction = null;
        transaction = session.beginTransaction();
        transaction.begin();
        session.save(kafkaMessage);
        transaction.commit();
        return kafkaMessage;
    } finally {
        //It will close session to avoid exception that it cannot get connection from pool
        if(session != null)
            session.close();
    }
}

如果您知道解决方法,请帮助我。非常感谢您的帮助

0 个答案:

没有答案