Shiyou
Shiyou

Reputation: 121

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
    }
}

Upvotes: 3

Views: 2092

Answers (2)

nuno
nuno

Reputation: 1791

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.

Upvotes: 1

Forketyfork
Forketyfork

Reputation: 7810

If you don't want to map this field at all, you could use @Transient annotation:

@Transient
private String password;

If you simply don't want to show this field when you convert the object to a particular JSON representation, then this is a data representation problem, not a ORM mapping problem. You should skip this field when you convert your object to JSON. The implementation depends on what JSON converter you are using. For instance, if you use Jackson, then the @JsonIgnore annotation is what you need.

Upvotes: 0

Related Questions