code_lover
code_lover

Reputation: 37

Update in EBean not working

I have following scenario using Play/EBean in Java

@Entity
public class Client extends Model {

    @javax.persistence.Id
    public Long Id;

    public String host;
    public String mac;
    public String os;
    public Integer cores;

    @OneToOne
    public Groups group;

    public Client(String host, String mac, String os, Integer cores, Groups group){
        this.mac = mac;
        this.host = host;
        this.os = os;
        this.cores = cores;
        this.group = group;
    }
// truncated
}

and

@Entity
public class Groups extends Model {

    @javax.persistence.Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    public Long Id;

    @Required
    public String groupName;

    @Required
    public String groupDescription;

    @Temporal(TemporalType.TIMESTAMP)
    @Column()
    public Date createTime;

    @OneToMany(mappedBy="group", cascade=CascadeType.PERSIST)
    public List<Client> clients = new ArrayList<>();

    public Groups(String name, String description){
        groupName = name;
        groupDescription = description;
        //clients = new ArrayList<>();
    }
}

I have getters and setters for fields.

The Client are stored in database already, and while creating a new Group I can assign the clients. Following code is used to save the Group.

public static Result save(){
        Form<Groups> boundForm = groupForm.bindFromRequest();
        if(boundForm.hasErrors())
        {
            flash("error", "Please correct the form below");
            //group.render(boundForm)
            return badRequest(group.render(boundForm, Client.findAll()));
        }
        Groups group = boundForm.get();
        HashMap<String, String> map = (HashMap<String, String>) boundForm.data();

        Long clientID = Long.parseLong(map.get("Client"));
        Client c = (Client) Ebean.find(Client.class,clientID);
        BeanState bs = Ebean.getBeanState(c);
        group.clients = new ArrayList<>();
        //group.clients.add(c);
        group.clients.add(new Client(c.getHost(), c.getMac(), c.getOS(), c.getCores(), c.getGroup()));
        Ebean.save(group);

        flash("success", String.format("Succesfully added group %s", group));
        //routes.GroupController.list()
        return redirect(routes.GroupController.list());
    }

The issue is a new record is inserted into the Client table instead of updating the previous one.

Upvotes: 2

Views: 2450

Answers (1)

biesior
biesior

Reputation: 55798

For saving new objects use save() (as you do)

For updating existing use update(id) instead

BTW, while you use public fields, you don't need to override getters/setters, Play does it automatically.

Upvotes: 2

Related Questions