Java基础阶段的⾃定义时间格式和id⾃增的实现
前⾔
这段时间⽤Java基础做了⼀个⼩项⽬的初级功能模块,该项⽬是为了⽅便⽤户购买⽹店商品,并且对⽤户购买的信息进⾏统⼀管理的系统。记录⼀下其中的时间格式转换和 id ⾃增。
⽤户的订单编号中包含创建订单时的⽇期,⽐如202008171001这样,后⾯的编号1001⾃动增加。
订单创建时间格式为创建时的⽇期时间,⽐如2020-08-17 18:41这样。
商品实体类的 id ⾃动增长。
说明:这⾥是纯 Java 实现,不涉及数据库等其他⽅⾯。
下⾯是我的代码实现:
订单类
订单实体类构造⽅法之⼀:
public Order(String name, String phone, String address, String deliveryMode){
// 时间格式模板
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMdd");
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
// 订单编号
// 当前⽇期⽬标格式 + (当前存储 id + 1)
// 创建时间
this.date = w().format(formatter2);
// 创建⼈
this.name = name;
// 联系⽅式
this.phone = phone;
// 联系地址
this.address = address;
// 派送⽅式
this.deliveryMode = deliveryMode;
// 覆盖之前存储 id 为当前 id
setUuid(getUuid()+1);
java时间日期格式转换}
通过以上⽅式将当前⽇期和当前时间的默认格式转换成⽬标格式并应⽤,其中的 getUuid() 和 setUuid() 两个⽅法就是利⽤ IO 流的DataInputStream 和 DataOutputStream 实现 id ⾃增,并且当前最新 id 存储在本地⽂件中,这就保证了断⽹或服务器关闭等情况不会对其产⽣太⼤影响。(注意:这⾥的 id 并不是完整的 orderId )
下⾯是⽤ IO 流实现 id ⾃增的⽅法:
private Integer getUuid(){
// 初始化 id
int id =1000;
// 读取存储的 id 数值
try(DataInputStream dis =new DataInputStream(
new FileInputStream("D:\\JAVA\\data\\currentOrderId"))){
id = adInt();
}catch(IOException e){
}
return id;
}
private void setUuid(Integer id){
// 写⼊覆盖更新当前 id
try(DataOutputStream dos =new DataOutputStream(
new FileOutputStream("D:\\JAVA\\data\\currentOrderId"))){
dos.writeInt(id);
}catch(IOException e1){
e1.printStackTrace();
}
}
因为⽂件⼀开始是空的,并没有任何数据,所以 getUuid() ⽅法先初始化 id 值,之后读取的时候会抛出
异常,并且捕获后⽆需处理。之后通过 setUuid() ⽅法把值写⼊到⽂件中,然后这样不断读取,不断覆盖,实现 id ⾃增。
还有⼀种简单的实现 id ⾃增的⽅法,不过仅限于服务器运⾏状态下,即 id 存储在内存中,数据是临时状态,不能永久保存。例如:
产品类
产品实体类属性:
private Integer id;
private static Integer guid =1001;
private String productName;
private Double price;
定义⼀个静态的标记 guid 属性,限制了其只初始化⼀次。
构造⽅法之⼀:
public Product(String productName, Double price){
this.id = guid++;
this.productName = productName;
this.price = price;
}
通过以上⽅式就可以实现 id 的不断⾃增,每创建⼀次对象,id 就加⼀。
补充
如果⽤数据库的话,嘿嘿…