Hi
I would like to create a mapping, that creates a tree of elements.
sql:
Code:
create table menu(
id INT unsigned AUTO_INCREMENT not null PRIMARY KEY,
name varchar(20) not null,
parent INT unsigned,
position INT unsigned,
content TEXT,
FOREIGN KEY (parent) REFERENCES menu(id)
);
Entity:
Code:
@Entity
@Table(name = "menu")
public class MenuItem{
@Id
@GeneratedValue
@Column(name = "id", nullable = false)
private Long id;
public Long getId() {
return id;
}
protected void setId(Long id) {
this.id = id;
}
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@IndexColumn(name = "position", base = 1)
private List<MenuItem> children;
public List<MenuItem> getChildren() {
return children;
}
public void setChildren(List<MenuItem> children) {
this.children = children;
}
@ManyToOne()
@JoinColumn()
private MenuItem parent;
public MenuItem getParent() {
return parent;
}
public void setParent(MenuItem parent) {
this.parent = parent;
}
...
}
I can delete elements, but if I would like to append one, nothing happens...
@Transactional()
public void append(MenuItem parent, MenuItem child){
parent.addChild(child);
em.persist(parent);
return;
}
I created an element to append, but both parent and position field remains <null>, and I can see only
the insert statement for that element, nothing more.
Code:
select
children0_.parent as parent1_,
children0_.id as id1_,
children0_.position as position1_,
children0_.id as id2_0_,
children0_.content as content2_0_,
children0_.name as name2_0_,
children0_.parent as parent2_0_,
children0_.position as position2_0_
from
menu children0_
where
children0_.parent=?
[DEBUG,TransactionSynchronizationManager,http-8080-5] Retrieved value [org.springframework.orm.jpa.EntityManagerHolder@1d13f05] for key [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean@af0e38] bound to thread [http-8080-5]
[DEBUG,TransactionSynchronizationManager,http-8080-5] Retrieved value [org.springframework.orm.jpa.EntityManagerHolder@1d13f05] for key [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean@af0e38] bound to thread [http-8080-5]
Hibernate:
insert
into
menu
(content, name, parent, position)
values
(?, ?, ?, ?)
I use the Spring framework for handling the transactions, and the org.springframework.transaction.annotation.Transactional annotation and Hibernate as JPA provider.
The removal code removes only the actual element, do not update the position of the others:
Code:
@Transactional()
public void remove(String id) throws EntityNotFoundException {
MenuItem item=getPage(id);
MenuItem parent=item.getParent();
parent.getChildren().remove(item);
em.merge(parent);
em.remove(item);
}
Any tips?
Thanks:
Bence