2016-06-28 91 views
2

下面是一个Entity名为Person:使用布尔值设置实体的字符串字段?

@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"; 
    } 

} 

使用上面的二传手,如果我要做到以下几点:

person.setPaidInFull(true); 

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

+0

你试过了吗? – marthursson

回答

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"; 
    } 
} 
+0

谢谢,所以基本上将该值设置为true会将数据库中的值设置为字符串值“Y”? – java123999

+0

是的,如果你的数据库类型接受一个字符串是(NVARCHAR等 – Igoranze

1

,你也可以尝试休眠 “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