简体   繁体   中英

How to save List in SQL database?

My entity class contains List of primefaces.model.map.Marker:

@Entity
@Table(name = "appuser")
public class UserEntity extends BaseEntity {

    private List<Marker> places = new ArrayList<Marker>();

    public List<Marker> getPlaces() {
    return places;
  }
}

Also, I have a sql file that describes my table. I know how to save String, double and other primitive types. But I don't know how to save arrays, collections of primitive types or collections with objects of my own type.

Could you help me with this, saving a list to Oracle DB?

I know that there exist different approaches to do this: save the list as a single string, as an object...

PS: It would be great if you could give me a reference to a site or book that describes the interaction between Java and SQL.

The usual DB representation of Lists is a separate table. Read about JPA's @OneToMany Annotation.

A good source for information on this topic is the JPA2 Specification (full of examples, but I've heard some people say it's hard to read / boring)

As Duckstep allready said, the usual

The usual DB representation of Lists is a separate table.

If you do not want to create a OtM connection in your database, you could create a helper class which puts the list in a String and splits the string into a list like the following:

public class Helper {

    public String stringify(List<Marker> l) {
        String rs = "";
        for (Marker marker : l) {
            rs = rs + ',' + marker.toString();
        }
        rs.substring(1);
        return rs;
    }

    public List<Marker> makeList(String rs){
        List<Marker> rl = new LinkedList<Marker>();
        String[] a = rs.split(",");
        for (String string : a) {
            Marker rm = new Marker();
            // I don't know what class of marker you use, 
            //but here you should create the marker from the string
            rl.add(rm);
        }
        return rl;
    }

}

But seriously! Its better to use a OtM table, as you are totally filling your Database with useless repetitions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM