为什么我会得到“对象引用了未保存的临时实例”的错误?

huangapple go评论82阅读模式
英文:

Why I get Object references an unsaved transient instance

问题

我在两个实体之间有多对多的关系:Tag 和 Ads。当用户想要创建广告时,需要插入一些标签。但是当我尝试创建广告时,我遇到了这个错误:

{
    "timestamp": "2020-10-11T21:21:44.752+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.mybrocki.entity.Tag; nested exception is java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.mybrocki.entity.Tag",
    "path": "/mybrocki/auth/ads/create"
}

这是我的 Tag 实体:

@Entity
@Table(name = "Tags")
public class Tag {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

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

    @ManyToMany(mappedBy = "adsTags", cascade = {
            CascadeType.ALL
    })
    private Set<Ads> ads;

    // 省略 getter 和 setter 方法...
}

这是 Ads 实体:

@ManyToMany
@JoinTable(name = "tags_ads",
    joinColumns = @JoinColumn(name = "ads_id", referencedColumnName = "id"),
    inverseJoinColumns = @JoinColumn(name = "tag_id", referencedColumnName = "id"))
private List<Tag> adsTags;

这是服务实现类的部分代码:

ads.setVisibleAds(false);
ads.setAdsTags(new ArrayList<Tag>());
if (!adsDTO.getTags().isEmpty()) {
    for (Tag tagDTO : adsDTO.getTags()) {
        ads.getAdsTags().add(tagDTO);
    }
}

// 其他属性的设置...

adsRepository.save(ads);

这是 JSON 数据:

{
    "adsGroupId": 5,
    "adsSubGroupId": 27,
    "adsType": "USED",
    "description": "Ford fiesta 1.3",
    "fixedPrice": false,
    "freeDelivery": false,
    "image": [
        "http://res.cloudinary.com/mybrocki/image/upload/v1589887253/s5d11rshydka5nov2wox.jpg,http://res.cloudinary.com/mybrocki/image/upload/v1589887253/s5d11rshydka5nov2wox.jpg,"
    ],
    "price": 800,
    "productName": "FOcscscsdcRD Goragjhggiujkjhkjoijiohiuhn",
    "productWarranty": false,
    "urgentSales": true,
    "tags": [
        {
            "name": "Second hand"
        }
    ]
}

可能的问题是什么?

英文:

I have many-to-many relationship between two entities: Tag and Ads. When User wants to create ad, he need to insert few tags. But when I try to create add I am getting this error:

{
    &quot;timestamp&quot;: &quot;2020-10-11T21:21:44.752+0000&quot;,
    &quot;status&quot;: 500,
    &quot;error&quot;: &quot;Internal Server Error&quot;,
    &quot;message&quot;: &quot;org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.mybrocki.entity.Tag; nested exception is java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.mybrocki.entity.Tag&quot;,
    &quot;path&quot;: &quot;/mybrocki/auth/ads/create&quot;
}

This is my Tag entity:

@Entity
@Table(name=&quot;Tags&quot;)
public class Tag {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;
	
	@Column(name=&quot;name&quot;)
	private String name;

	@ManyToMany(mappedBy = &quot;adsTags&quot;,  cascade = {
	        CascadeType.ALL
	    })
	private Set&lt;Ads&gt; ads;
	
	
	public Long getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public Set&lt;Ads&gt; getAds() {
		return ads;
	}

	public void setAds(Set&lt;Ads&gt; ads) {
		this.ads = ads;
	}

And this is Ads entity:

@ManyToMany
    @JoinTable(name = &quot;tags_ads&quot;,
        joinColumns = @JoinColumn(name = &quot;ads_id&quot;, referencedColumnName = &quot;id&quot;),
        inverseJoinColumns = @JoinColumn(name = &quot;tag_id&quot;, referencedColumnName = &quot;id&quot;))
	private List&lt;Tag&gt; adsTags;

And this is service implementation class:

ads.setVisibleAds(false);
					ads.setAdsTags(new ArrayList&lt;Tag&gt;());
					if (!adsDTO.getTags().isEmpty()) {
						for (Tag tagDTO : adsDTO.getTags()) {
					ads.getAdsTags().add(tagDTO); }
					

					}
					ads.setStatus(AdsStatus.READYFORREVIEW.toString());
					ads.setAdssubgroup(adsSubGroupRepository.findOneById(adsDTO.getAdsSubGroupId()));
					ads.setFixedPrice(adsDTO.getFixedPrice());
					ads.setFreeDelivery(adsDTO.getFreeDelivery());
					ads.setProductWarranty(adsDTO.getProductWarranty());
					ads.setUrgentSales(adsDTO.getUrgentSales());
					Date currentDate = new Date();
					Instant instant = currentDate.toInstant();
					LocalDateTime ldt = instant.atOffset(ZoneOffset.UTC).toLocalDateTime();
					DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;yyyy-MM-dd&quot;);
					
					adsDTO.setAdsDate(currentDate);
					ads.setAdsDate(adsDTO.getAdsDate());
					
					adsRepository.save(ads);

This is json:

{
  &quot;adsGroupId&quot;: 5,
  &quot;adsSubGroupId&quot;: 27,
  &quot;adsType&quot;: &quot;USED&quot;,
  &quot;description&quot;: &quot;Ford fiesta 1.3&quot;,
  &quot;fixedPrice&quot;: false,
  &quot;freeDelivery&quot;: false,
  &quot;image&quot;: [
    &quot;http://res.cloudinary.com/mybrocki/image/upload/v1589887253/s5d11rshydka5nov2wox.jpg,http://res.cloudinary.com/mybrocki/image/upload/v1589887253/s5d11rshydka5nov2wox.jpg,&quot;
  ],
  &quot;price&quot;: 800,
  &quot;productName&quot;: &quot;FOcscscsdcRD Goragjhggiujkjhkjoijiohiuhn&quot;,
  &quot;productWarranty&quot;: false,
  &quot;urgentSales&quot;: true,
    &quot;tags&quot;: [
        {
        &quot;name&quot;:&quot;Second hand&quot;
    }]
}

What could be the problem?

答案1

得分: 2

你的 Tag 类上有 cascade = {CascadeType.ALL },但是你的 Ads 类上却没有,如果你想保存你的 Ads 对象并级联保存其中的 Tag 对象,那么你需要在 Ads 类的字段上加上这个注解。否则,请保存 Tag 对象而不是 Ads 对象。

英文:

You have cascade = {CascadeType.ALL } on your Tag class but not on your Ads class, if you want to save your Ads object and cascade save the Tag objects in it, then you need the annotation on the field of your Ads class. Otherwise save the Tag object instead of the Ads object.

huangapple
  • 本文由 发表于 2020年10月12日 05:29:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/64309202.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定