I use Hibernate to control my database and I have 2 tables:
CREATE TABLE IF NOT EXISTS `User`(
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL DEFAULT '',
`account` VARCHAR(255) NOT NULL DEFAULT '',
`password` VARCHAR(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
)
CREATE TABLE IF NOT EXISTS `Project` (
`id` INT NOT NULL AUTO_INCREMENT,
`manager` INT NOT NULL,
`name` VARCHAR(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
FOREIGN KEY (`manager`) REFERENCES `User`(`id`)
)
And I have done the mapping:
User:
// ... import code
@Entity
@Table
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column
private String name, account, password;
@OneToMany(mappedBy = "manager")
private List<Project> projects;
public User() {
}
// ... Getter & Setter code
}
Project:
// ... import code
@Entity
@Table
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column
private String name;
@ManyToOne
@JoinColumn(name = "manager")
private User manager;
public Project () {
}
// ... Getter & Setter code
}
I want to know whether it is possible when I select projects, the project will include its manager data but not have password.
In other ways, I want that each project I get will like this (format as JSON):
{
"id": 0,
"name": "A test project",
"manager": {
"id": 0,
"name": "John Smith"
"accound": "user1",
"password": null
}
}
A projection could be used to limit the fields you want to bring into memory, you could get a projection of all fields except the password.
Another option can be adding the lazy annotation to the field:
@Basic(fetch = FetchType.LAZY)
@Column(...)
private String password;
Another way would be to use a direct HQL query and load only the required fields, from this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With