У меня есть два класса, класс блога:
Entity
@Table(name = "Blog_table")
public class Blog {
@Id
@NotNull
@Column(name="id")
@GeneratedValue(generator = "incrementator")
@GenericGenerator(name = "incrementator", strategy = "increment" )
private int id;
@Column(name = "blog_title")
private String blog_title;
@Column(name = "dateTime")
private LocalDateTime creation_date = LocalDateTime.now();
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "User_id")
private User user;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "Category_id")
private Category category;
@Column(name = "tags")
private String tags;
//getters,setters,constructors
и класс категории, который выглядит следующим образом:
@Entity
@Table(name = "Category_table")
public class Category {
@Id
@NotNull
@Column(name="id")
@GeneratedValue(generator = "incrementator")
@GenericGenerator(name = "incrementator", strategy = "increment" )
private int id;
@Column(name = "name")
private String name;
@OneToMany(
mappedBy = "category",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<Blog> blogs = new ArrayList<>();
public void addBlog(Blog blog){
blogs.add(blog);
blog.setCategory(this);
}
public void removeBlog(Blog blog){
blogs.remove(blog);
blog.setCategory(null);
}
//getters,setters,constructors
У меня есть форма создания, которая выглядит следующим образом
@(blogForm: Form[Blog],categories : Seq[Category])
@import helper.inputText, helper.textarea, helper.select
@base(title = "Create a blog") {
<div class = "container-field">
<div class="text-center"><h1><strong>Crate your blog and let the fun begin!</strong></h1></div>
<br><br>
<div class = "row">
<div class = "col-md-4 col-md-offset-4">
@helper.form(action = routes.BlogController.save_Blog()) {
@inputText(blogForm("blog_title"), '_label -> "", 'placeholder -> "Your blog title", 'class -> "form-control")
@inputText(blogForm("tags"), '_label -> "", 'placeholder -> "Tags", 'class -> "form-control")
@select(field = blogForm("Category"), options = categories.map(category => category.getId.toString -> category.getName) )
<div class="text-center">
<button type="submit" class="btn btn-link">  Create your blog  </button>
</div>
}
</div>
</div>
</div>
}
Как получить значение выбранного параметра, добавить этот блог в категорию и сохранить его?Значением поля выбора является идентификатор категории, но как мне получить к нему доступ?Класс контроллера выглядит следующим образом:
@Inject
FormFactory formFactory;
public Result create_Blog(){
Form<Blog> blogForm = formFactory.form(Blog.class);
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("defaultPersistenceUnit");
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
List<Category> categories_list = entityManager.createQuery("from Category ").getResultList();
Seq<Category> categories = JavaConverters.asScalaBuffer(categories_list).toSeq();
entityManager.getTransaction().commit();
entityManagerFactory.close();
return ok(blog_create.render(blogForm,categories));
}
public Result save_Blog(){
Form<Blog> blogForm = formFactory.form(Blog.class).bindFromRequest();
Blog blog = blogForm.get();
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("defaultPersistenceUnit");
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
User user = entityManager.createQuery("from User where name='"+Secured.getName(ctx())+"'",User.class).getSingleResult();
user.addBlog(blog);
System.out.println(blog);
entityManager.persist(user);
entityManager.getTransaction().commit();
entityManagerFactory.close();
return redirect(routes.HomeController.index());
}
Мне нужно получить значение, чтобы написать что-то вроде:
Category category = entityManager.find(Category.class, id);
category.addBlog(blog);