1.创建Person类,Person的属性有: Strng name 姓名 String sex 性别 Integer age 年龄, String idNo 身份证号 Boolean isMerried 是否已婚 请生成相应的getter、setter方法。请编写注解@Label,表示所注解对象的中文名称,请把@Label注解标注在Person类和Person的每个属性上面。请编写PersonInput类,负责提示录入人员的相关属性,提示必须是注解@Label所标注的中文名称。请编写PersonDisplay,负责显示人员信息,显示时的属性名称必须为注解@Label所标注的中文名称,PersonInput类与PersonDisplay类实现了共同的接口PersonAction,接口PersonAction有方法process,方法process的签名为:public Person process(Person person); 2.在第一题目的基础上,编写注解@Column,属性有Label 表示类的属性的显示名称,Nullable 表示是否允许属性值为空,MaxLength 表示文本属性的最大长度,MinLength表示文本属性的最小长度,MaxValue表示最大值,MinValue表示最小值,把注解@Column加在Person类的每个属性上,在输入Person时根据注解@Column的配置进行校验。第一题的@Label只标注在类上。根据注解生成Person类对应的数据库表创建语句,以及生成数据库表的删除、新增、修改SQL语句。 并利用JDBC,实现数据库操作。只生成第二题代码
时间: 2023-06-18 08:08:45 浏览: 158
先给出完整代码,再一步步解释。
```java
import java.lang.annotation.*;
import java.util.Scanner;
public class PersonInput implements PersonAction {
private static Scanner input = new Scanner(System.in);
@Override
public Person process(Person person) {
Class cls = person.getClass();
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
boolean isAccess = field.isAccessible();
if (!isAccess) {
field.setAccessible(true);
}
Label label = field.getAnnotation(Label.class);
Column column = field.getAnnotation(Column.class);
if (label != null) {
System.out.print(label.value() + ": ");
}
if (column != null) {
String inputStr = input.nextLine();
if (!column.nullable() && (inputStr == null || inputStr.length() == 0)) {
System.out.println(column.label() + "不能为空");
inputStr = input.nextLine();
}
if (column.maxLength() > 0 && inputStr.length() > column.maxLength()) {
System.out.println(column.label() + "长度不能超过" + column.maxLength() + "个字符");
inputStr = input.nextLine();
}
if (column.minLength() > 0 && inputStr.length() < column.minLength()) {
System.out.println(column.label() + "长度不能少于" + column.minLength() + "个字符");
inputStr = input.nextLine();
}
if (column.maxValue() > Long.MIN_VALUE) {
long value = Long.parseLong(inputStr);
if (value > column.maxValue()) {
System.out.println(column.label() + "不能大于" + column.maxValue());
inputStr = input.nextLine();
}
}
if (column.minValue() < Long.MAX_VALUE) {
long value = Long.parseLong(inputStr);
if (value < column.minValue()) {
System.out.println(column.label() + "不能小于" + column.minValue());
inputStr = input.nextLine();
}
}
try {
if (field.getType() == String.class) {
field.set(person, inputStr);
} else if (field.getType() == Integer.class) {
int value = Integer.parseInt(inputStr);
field.set(person, value);
} else if (field.getType() == Long.class) {
long value = Long.parseLong(inputStr);
field.set(person, value);
} else if (field.getType() == Boolean.class) {
boolean value = Boolean.parseBoolean(inputStr);
field.set(person, value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (!isAccess) {
field.setAccessible(false);
}
}
return person;
}
}
import java.lang.annotation.*;
public class PersonDisplay implements PersonAction {
@Override
public Person process(Person person) {
Class cls = person.getClass();
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
boolean isAccess = field.isAccessible();
if (!isAccess) {
field.setAccessible(true);
}
Label label = field.getAnnotation(Label.class);
if (label != null) {
try {
System.out.println(label.value() + ": " + field.get(person));
} catch (Exception e) {
e.printStackTrace();
}
}
if (!isAccess) {
field.setAccessible(false);
}
}
return person;
}
}
@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface Label {
String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Column {
String label();
boolean nullable() default true;
int maxLength() default 0;
int minLength() default 0;
long maxValue() default Long.MIN_VALUE;
long minValue() default Long.MAX_VALUE;
}
interface PersonAction {
Person process(Person person);
}
class Person {
@Label("姓名")
@Column(label = "姓名", nullable = false, maxLength = 32)
private String name;
@Label("性别")
@Column(label = "性别")
private String sex;
@Label("年龄")
@Column(label = "年龄", minValue = 0, maxValue = 200)
private Integer age;
@Label("身份证号")
@Column(label = "身份证号", maxLength = 18)
private String idNo;
@Label("是否已婚")
@Column(label = "是否已婚")
private Boolean isMarried;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getIdNo() {
return idNo;
}
public void setIdNo(String idNo) {
this.idNo = idNo;
}
public Boolean getMarried() {
return isMarried;
}
public void setMarried(Boolean married) {
isMarried = married;
}
}
public class Main {
private static final String CREATE_TABLE_SQL = "CREATE TABLE `person` (\n" +
" `id` int(11) NOT NULL AUTO_INCREMENT,\n" +
" `name` varchar(32) NOT NULL,\n" +
" `sex` varchar(8) DEFAULT NULL,\n" +
" `age` int(11) DEFAULT NULL,\n" +
" `id_no` varchar(18) DEFAULT NULL,\n" +
" `married` tinyint(1) DEFAULT NULL,\n" +
" PRIMARY KEY (`id`)\n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
private static final String DROP_TABLE_SQL = "DROP TABLE IF EXISTS `person`;";
private static final String INSERT_SQL = "INSERT INTO `person` (`name`, `sex`, `age`, `id_no`, `married`) VALUES (?, ?, ?, ?, ?);";
private static final String UPDATE_SQL = "UPDATE `person` SET `name`=?,`sex`=?,`age`=?,`id_no`=?,`married`=? WHERE `id`=?;";
private static final String DELETE_SQL = "DELETE FROM `person` WHERE `id`=?;";
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8", "root", "123456");
Statement stmt = conn.createStatement();
stmt.executeUpdate(DROP_TABLE_SQL);
stmt.executeUpdate(CREATE_TABLE_SQL);
PersonInput input = new PersonInput();
PersonDisplay display = new PersonDisplay();
Person person = new Person();
input.process(person);
display.process(person);
ps = conn.prepareStatement(INSERT_SQL);
ps.setString(1, person.getName());
ps.setString(2, person.getSex());
ps.setInt(3, person.getAge());
ps.setString(4, person.getIdNo());
ps.setBoolean(5, person.getMarried());
ps.executeUpdate();
ps = conn.prepareStatement(UPDATE_SQL);
ps.setString(1, person.getName());
ps.setString(2, person.getSex());
ps.setInt(3, person.getAge());
ps.setString(4, person.getIdNo());
ps.setBoolean(5, person.getMarried());
ps.setInt(6, 1);
ps.executeUpdate();
ps = conn.prepareStatement(DELETE_SQL);
ps.setInt(1, 1);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
```
首先,我们定义了两个注解,@Label和@Column。其中,@Label是用来给类和属性添加中文名称的,@Column是用来给属性添加数据库字段的一些配置信息的。
```java
@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface Label {
String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Column {
String label();
boolean nullable() default true;
int maxLength() default 0;
int minLength() default 0;
long maxValue() default Long.MIN_VALUE;
long minValue() default Long.MAX_VALUE;
}
```
然后,我们定义了一个Person类,它有姓名、性别、年龄、身份证号、是否已婚等属性,每个属性都添加了@Label和@Column注解。我们使用注解处理器,可以根据@Column注解的配置信息来进行输入校验,这样就可以避免输入错误的数据。同时,我们还定义了PersonInput和PersonDisplay两个类,它们都实现了PersonAction接口,分别用于输入和输出一个Person对象。
```java
class Person {
@Label("姓名")
@Column(label = "姓名", nullable = false, maxLength = 32)
private String name;
@Label("性别")
@Column(label = "性别")
private String sex;
@Label("年龄")
@Column(label = "年龄", minValue = 0, maxValue = 200)
private Integer age;
@Label("身份证号")
@Column(label = "身份证号", maxLength = 18)
private String idNo;
@Label("是否已婚")
@Column(label = "是否已婚")
private Boolean isMarried;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getIdNo() {
return idNo;
}
public void setIdNo(String idNo) {
this.idNo = idNo;
}
public Boolean getMarried() {
return isMarried;
}
public void setMarried(Boolean married) {
isMarried = married;
}
}
interface PersonAction {
Person process(Person person);
}
public class PersonInput implements PersonAction {
@Override
public Person process(Person person) {
Class cls = person.getClass();
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
boolean isAccess = field.isAccessible();
if (!isAccess) {
field.setAccessible(true);
}
Label label = field.getAnnotation(Label.class);
Column column = field.getAnnotation(Column.class);
if (label != null) {
System.out.print(label.value() + ": ");
}
if (column != null) {
String inputStr = input.nextLine();
if (!column.nullable() && (inputStr == null || inputStr.length() == 0)) {
System.out.println(column.label() + "不能为空");
inputStr = input.nextLine();
}
if (column.maxLength() > 0 && inputStr.length() > column.maxLength()) {
System.out.println(column.label() + "长度不能超过" + column.maxLength() + "个字符");
inputStr = input.nextLine();
}
if (column.minLength() > 0 && inputStr.length() < column.minLength()) {
System.out.println(column.label() + "长度不能少于" + column.minLength() + "个字符");
inputStr = input.nextLine();
}
if (column.maxValue() > Long.MIN_VALUE) {
long value = Long.parseLong(inputStr);
if (value > column.maxValue()) {
System.out.println(column.label() + "不能大于" + column.maxValue());
inputStr = input.nextLine();
}
}
if (column.minValue() < Long.MAX_VALUE) {
long value = Long.parseLong(inputStr);
if (value < column.minValue()) {
System.out.println(column.label() + "不能小于" + column.minValue());
inputStr = input.nextLine();
}
}
try {
if (field.getType() == String.class) {
field.set(person, inputStr);
} else if (field.getType() == Integer.class) {
int value = Integer.parseInt(inputStr);
field.set(person, value);
} else if (field.getType() == Long.class) {
long value = Long.parseLong(inputStr);
field.set(person, value);
} else if (field.getType() == Boolean.class) {
boolean value = Boolean.parseBoolean(inputStr);
field.set(person, value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (!isAccess) {
field.setAccessible(false);
}
}
return person;
}
}
public class PersonDisplay implements PersonAction {
@Override
public Person process(Person person) {
Class cls = person.getClass();
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
boolean isAccess = field.isAccessible();
if (!isAccess) {
field.setAccessible(true);
}
Label label = field.getAnnotation(Label.class);
if (label != null) {
try {
System.out.println(label.value() + ": " + field.get(person));
} catch (Exception e) {
e.printStackTrace();
}
}
if (!isAccess) {
field.setAccessible(false);
}
}
return person;
}
}
```
最后,我们在Main类中使用JDBC,将Person对象保存到数据库中。在保存之前,先执行了一次删除表和创建表的操作。
```java
public class Main {
private static final String CREATE_TABLE_SQL = "CREATE TABLE `person` (\n" +
" `id` int(11) NOT NULL AUTO_INCREMENT,\n" +
" `name` varchar(32) NOT NULL,\n" +
" `sex` varchar(8) DEFAULT NULL,\n" +
" `age` int(11) DEFAULT NULL,\n" +
" `id_no` varchar(18) DEFAULT NULL,\n" +
" `married` tinyint(1) DEFAULT NULL,\n" +
" PRIMARY KEY (`id`)\n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
private static final String DROP_TABLE_SQL = "DROP TABLE IF EXISTS `person`;";
private static final String INSERT_SQL = "INSERT INTO `person` (`name`, `sex`, `age`, `id_no`, `married`) VALUES (?, ?, ?, ?, ?);";
private static final String UPDATE_SQL = "UPDATE `person` SET `name`=?,`sex`=?,`age`=?,`id_no`=?,`married`=? WHERE `id`=?;";
private static final String DELETE_SQL = "DELETE FROM `person` WHERE `id`=?;";
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8", "root", "123456");
Statement stmt = conn.createStatement();
stmt.executeUpdate(DROP_TABLE_SQL);
stmt.executeUpdate(CREATE_TABLE_SQL);
PersonInput input = new PersonInput();
PersonDisplay display = new PersonDisplay();
Person person = new Person();
input.process(person);
display.process(person);
ps = conn.prepareStatement(INSERT_SQL);
ps.setString(1, person.getName());
ps.setString(2, person.getSex());
ps.setInt(3, person.getAge());
ps.setString(4, person.getIdNo());
ps.setBoolean(5, person.getMarried());
ps.executeUpdate();
ps = conn.prepareStatement(UPDATE_SQL);
ps.setString(1, person.getName());
ps.setString(2, person.getSex());
ps.setInt(3, person.getAge());
ps.setString(4, person.getIdNo());
ps.setBoolean(5, person.getMarried());
ps.setInt(6, 1);
ps.executeUpdate();
ps = conn.prepareStatement(DELETE_SQL);
ps.setInt(1, 1);
阅读全文