java sql根據查詢結果,轉換成自己想要的數據

pojo:

@Data
public class Student {

    private int id;

    private String name;

    private int age;

    private String sex;
    
}

場景:數據庫裏面字段sex數據類型是bit,想在java中用String表示。

想法:將查詢出來的sql結果,將字段sex由bit數據類型(數據庫中是bit,java中用boolean表示)轉換成String數據類型。

解決辦法:

select id,name,case when sex=0 then '男' else '女' end as sex from student

注意: case when 使用結束後,一定要加上as xxx(需要的成員對象名稱),如果不加的話會是null,如下圖:

 @Select("select id,name,case when sex=0 then '男' else '女' end 
 from student where id=#{id}")

 Student findById(int id);

 查詢結果:
 Student(id=1, name=zbz, age=0, sex=null)

加上as xxx的結果圖如下:

 @Select("select id,name,case when sex=0 then '男' else '女' end as sex
 from student where id=#{id}")

 Student findById(int id);

 查詢結果:
 Student(id=1, name=zbz, age=0, sex='男')

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章