简体   繁体   中英

Spring MVC Hibernate - Save object with multiple checkboxes

I'm trying to understand how can I save an employee with multiple tasks. But I don't know even how to start.

在此处输入图片说明

// Employee class
@Entity
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private int idNumber;
    private String firstName;
    private String lastName;

    @ManyToOne
    @JoinColumn(name = "task_id")
    private Set<Task> tasks = new HashSet<Task>();

}

// Task class
@Entity
public class Task {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
}

// Dao
@Override
public void saveEmployee(Employee employee) {
    sessionFactory.getCurrentSession().save(employee);
} 

// Controller
@RequestMapping(value = "/save", method = RequestMethod.POST)
public @ResponseBody void saveEmployee(@RequestBody Employee employee){
    employeeRepository.saveEmployee(employee)
}

I'll really appreciate if you refer documentation or code of any related example.

What you want is a @OneToMany on a List or Set in your Employee` class.

Here is a link to a tutorial put out by Baeldung.com. It goes over Hibernate and One To Many relationship based on a Cart (shopping cart) having multiple Item . Similarly you have an Employee with an Employee having multiple Task .

The tutorial uses a Set<Item> but you could also use a List<Item> as well.

http://www.baeldung.com/hibernate-one-to-many

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