使用布尔值设置实体的String字段?

时间:2016-06-28 09:09:58

标签: java string boolean entity setter

以下是名为Person的Entity

@Entity
@Table(
    name = "PERSON"
)
public class Person {

    //other fields etc

    @Column(
        name = "PAID_IN_FULL",
        nullable = false
    )
    private String paidInFull;

   public void setPaidInFull(boolean paidInFull) {
        this.paidInFull = paidInFull?"Y":"N";
    }

}

使用上面的setter,如果我要执行以下操作:

person.setPaidInFull(true);

将其设置为什么字符串值,是"Y"还是"N"

2 个答案:

答案 0 :(得分:1)

paidInFull?"Y":"N";

如果说:

是另一种方式
if (paidInFull)
    return "Y";
else
    return "N";

所以,如果你要做

person.setPaidInFull(true);

this.paidInFull将是“Y”。

这是一个完整的例子:

package nl.testing.startingpoint;

public class Main {
    private static String paidInFull;

    public static void main(String args[])
    {
        setPaidInFull(true);
        System.out.println(paidInFull);
    }

    public static void setPaidInFull(boolean paidInFull) {
        Main.paidInFull = (paidInFull) ? "Y" : "N";
    }
}

答案 1 :(得分:1)

你也可以试试hibernate" yes_no"类型。

import org.hibernate.annotations.Type;

@Entity
@Table(name = "PERSON")
public class Person {

     //other fields etc

     @Column(name = "PAID_IN_FULL", nullable = false)
     @Type(type = "yes_no")
     private Boolean paidInFull;

     public void setPaidInFull(boolean paidInFull) {
          this.paidInFull = paidInFull
     }

}

请参阅https://dzone.com/articles/mapping-boolean-y-or-n-using