@Column(columnDefinition)的使用

columnDefinition属性的使用:

@Table(name = "CUSTOMERS")
@Entity
public class Customer {
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    private Integer id;
    @Column(name = "Name")
    private String name;
    @Column(name = "Email",columnDefinition="varchar(128) not null")
    private String email;
    @Column(name = "Age")
    private int age;
    ......
}

数据库DDL:

CREATE TABLE `customers` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Age` int(11) DEFAULT NULL,
  `Email` varchar(128) NOT NULL,
  `Name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

columnDefinition可以指定创建表时一些SQL语句,比如这里可以一次性指定,varchar长度128,且不能为空 
当然,相同的结果可以通过nullable和length属性结合实现

@Table(name = "CUSTOMERS")
@Entity
public class Customer {
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    private Integer id;
    @Column(name = "Name")
    private String name;
    @Column(name = "Email", nullable = true, length = 128)
    private String email;
    @Column(name = "Age")
    private int age;
    ......
}

数据库DDL:

CREATE TABLE `customers` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Age` int(11) DEFAULT NULL,
  `Email` varchar(128) DEFAULT NULL,
  `Name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

columnDefinition属性的特殊使用:
编程语言中字符串一般都用String表示,但是数据库中varcahr数值类型有长度限制,一旦需要大文本,则需要text数值类型
但是String类型默认映射的数值类型是varchar,columnDefinition可以进行额外指定

@Table(name = "CUSTOMERS")
@Entity
public class Customer {
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    private Integer id;
    @Column(name = "Name")
    private String name;
    @Column(name = "Email", nullable = true, length = 128)
    private String email;
    @Column(name = "Age")
    private int age;
    @Column(name = "Remark",columnDefinition="text")
    private String remark;
    ......
}

数据库DDL:

CREATE TABLE `customers` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Age` int(11) DEFAULT NULL,
  `Email` varchar(128) DEFAULT NULL,
  `Name` varchar(255) DEFAULT NULL,
  `Remark` text,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

remark列数值类型是text,而Name和Email默认是varcahr

posted @ 2019-03-20 11:52  门罗的魔术师  阅读(15595)  评论(0编辑  收藏  举报