Can Hibernate select the join table without including some rows

I am using Hibernate to manage 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 did 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 if this is possible, when I select projects, the project will include its manager details, but not have a password.

In other words, I want every project I get to like it (format as JSON):

{
    "id": 0,
    "name": "A test project",
    "manager": {
        "id": 0,
        "name": "John Smith"
        "accound": "user1",
        "password": null
    }
}

      

+3


source to share


2 answers


1. Projection

A projection can be used to constrain the fields you want to write to memory, you can get a projection of all fields except password

.

2. Lazy

Another option could be to add a 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 only load the required fields from this answer .

+1


source


If you don't want to display this field at all, you can use the annotation @Transient

:

@Transient
private String password;

      



If you just don't want to show this field when converting an object to a specific JSON representation, then this is a data presentation issue, not an ORM mapping issue. You must skip this field when converting your object to JSON. The implementation depends on which JSON converter you are using. For example, if you are using Jackson, then annotation @JsonIgnore

is what you need.

0


source







All Articles