使用JPA将arraylist存储在mysql数据库中

时间:2015-12-09 13:58:56

标签: java mysql hibernate jpa arraylist

我正在尝试使用JPA和Hibernate向我的mysql数据库添加一个double值的arraylist,但它不是将值存储为double,它存储了arraylist对象,然后是很多字符。

下面的图片是数据库的样子。

Arraylist

这是我的代码:

Playlist.java

@Entity
public class Playlist {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

private String name, persistentId;
private double playlistId;
@ElementCollection
@CollectionTable(name ="tracks")
private ArrayList<Double> tracks = new ArrayList<Double>();

@OneToMany(mappedBy="playlist") 
Set<Song> songs;

public Playlist(String name, String persistentId, double playlistId, ArrayList<Double> tracks) {
    this.name = name;
    this.persistentId = persistentId;
    this.playlistId = playlistId;
    this.tracks = tracks;
}

public Playlist() {
}

Main.java

Playlist p = new Playlist();
ArrayList<Double> tracks = new ArrayList<Double>();
        for (int j = 0; j < tList.getLength(); ++j) {
            Element track = (Element) tList.item(j);

            Double trackId = (Double) x.evaluate("key[.='Track ID']/following-sibling::integer[1]", track,
                    XPathConstants.NUMBER);
            tracks.add(trackId);
            p.setTracks(tracks);

        }

有人可以告诉我,我做错了吗?

2 个答案:

答案 0 :(得分:1)

尝试设置更多信息:

@ElementCollection
@CollectionTable(name ="tracks" , joinColumns=@JoinColumn(name="playlist_id"))
@Column(name="track")
private List<Double> tracks = new ArrayList<>();

答案 1 :(得分:0)

您正在映射List接口的特定实现。 Hibernate使用它自己的实现,所以我的猜测是它会被它抛弃。非常奇怪,尽管它并没有失败......

尝试将其更改为:

@ElementCollection
@CollectionTable(name ="tracks")
private List<Double> tracks = new ArrayList<>();

new ArrayList<>()部分只是为了使其安全无效..)