Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Hibernate select a join table without including some rows

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
    }
}
like image 937
Shiyou Avatar asked Dec 14 '25 12:12

Shiyou


1 Answers

1. Projection

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.

2. Lazy

Another option can be adding the lazy annotation to the field:

@Basic(fetch = FetchType.LAZY)
@Column(...)
private String password;

3. HQL query

Another way would be to use a direct HQL query and load only the required fields, from this answer.

like image 125
nuno Avatar answered Dec 17 '25 06:12

nuno