白云点缀的蓝 发表于 2021-6-26 13:17

基于mysql的java管理系统

本帖最后由 starry、星空 于 2021-6-26 13:23 编辑

用到的技术主要就是mysql,idworker,雪花算法生成唯一的id,
这个管理系统是一个学生找我帮它做的,电脑放太久了,删除了也不太好,就分享出来吧,就一个命令行的管理系统,
还没用到maven依赖,也没有用到一些spring的框架,也没写前端页面,挺简单的一个管理系统,


主方法

package main.java;

import com.manageSystem.pojo.t_user;
import main.java.com.manageSystem.pojo.t_orderitem;
import main.java.com.manageSystem.pojo.t_orders;
import main.java.com.manageSystem.service.Service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class main {
    private static Scanner scanner = new Scanner(System.in);
    privatestatic t_user user;//用户信息保存
    private static String []argsSave={};
    public static void main(String[] args) throws Exception {
      argsSave=args;
      System.out.println("---------欢迎来到商品管理系统---------------------\n" +
                "1 用户登录\n" +
                "2 用户注册\n" +
                "3 退出系统\n" +
                "请输入选择:");

      int i = scanner.nextInt();
      switch (i){
            case 1:Login();
            break;
            case 2:signUp();
            break;
            case 3:exitSytem();
            break;
      }
    }

    //退出系统
    private static void exitSytem() {
      System.exit(0);
    }
    //用户注册
    private static void signUp() throws Exception {
      System.out.println("请输入用户名:");
      String username = scanner.next();
      System.out.println("请输入密码:");
      String password = scanner.next();
      try {
            new Service().addUser(username,password);
            System.out.println("注册成功");
      }catch (Exception e){
            System.out.println("注册失败");
      }finally {
            main(argsSave);
      }

    }
    //用户登录
    private static void Login() throws Exception {
      System.out.println("请输入用户名:");
      String username = scanner.next();
      System.out.println("请输入密码:");
      String password = scanner.next();
      try {
            user= new Service().findUser(username, password);
            if(user!=null){
                System.out.println(user);
                System.out.println("登录成功");
                manageSystem();
            }else {
                System.out.println("账号或密码不存在,请重新输入");
                main(argsSave);
            }
      }catch (Exception e){
            e.printStackTrace();
      }
    }
    //商品管理模块
    private static void manageSystem() throws Exception {
      System.out.println("-----------进入到商品管理模块-----------------\n" +
                "1 商品查询\n" +
                "2 商品修改\n" +
                "3 商品删除\n" +
                "4 商品添加\n" +
                "5 商品购买\n" +
                "6 查询用户订单\n" +
                "7 退出当前用户");
      int i = scanner.nextInt();
      switch (i){
            case 1:
                findGoods();
                break;
            case 2:
                editGoods();
                break;
            case 3:
                deleteGoods();
                break;
            case 4:
                addGoods();
                break;
            case 5:
                buyGoods();
                break;
            case 6:
                findUserOrderItems();
                break;
            case 7:
                user=null;
                main(argsSave);
                break;
      }
    }
    //查询用户订单
    private static void findUserOrderItems() throws Exception {
      List<t_orderitem> userOrderItems = Service.findUserOrderItems(user);
      ArrayList<t_orders> userOrders = Service.findUserOrders(user);
      for (int i = 0; i < userOrderItems.size(); i++) {
            System.out.println("订单项id"+userOrderItems.get(i).getoItemid());
            System.out.println("总金额"+userOrderItems.get(i).getoSubtotal());
            System.out.println("下单个数"+userOrderItems.get(i).getoCount());
            System.out.println("单价:"+userOrders.get(i).getoTotal());
            System.out.println("商品名字:"+userOrders.get(i).getoName());
      }
      manageSystem();
    }
    //商品添加
    private static void addGoods() throws Exception {
      System.out.println("请输入你要添加的商品名字:");
      String name = scanner.next();
      System.out.println("请输入你要添加的商品价格:");
      Double price = scanner.nextDouble();
      System.out.println("请输入你要添加的商品的状态:0为删除,1为正常");
      Integer status = scanner.nextInt();
      try {
            Service.addGoods(name,price,status);
            System.out.println("添加成功");

      }catch (Exception e){
            e.printStackTrace();
            System.out.println("添加失败");
      }finally {
            manageSystem();
      }

    }
    //商品购买
    private static void buyGoods() throws Exception {
      System.out.println("请输入要购买的商品名称:");
      String next = scanner.next();
      System.out.println("请输入商品数量:");
      int i = scanner.nextInt();
      System.out.println("是否提交订单 y or n (提示:输入n:继续提示:请输入要购买的商品名称、请输入要购买的数量)");
      String next1 = scanner.next();
      switch (next1){
            case "y":
                Service.addGoodsOrder(next,i,user);
                manageSystem();
                break;
            case "n":
                buyGoods();
                break;
      }
    }
    //商品删除
    private static void deleteGoods() {
    }
    //商品修改
    private static void editGoods() throws Exception {
      System.out.println("请选择修改选项:\n" +
                "1 修改名称\n" +
                "2 修改价格\n" +
                "3 修改商品描述\n" +
                "4 退到上一层菜单");
      int i = scanner.nextInt();
      switch (i){
            case 4:manageSystem();
            break;
      }
    }
    //商品查询
    private static void findGoods() throws Exception {
      System.out.println("请选择查询选项:\n" +
                "1 根据商品id查询:\n" +
                "2 根据商品名称查询(模糊查询)\n" +
                "3 退到上一层菜单");
      int i = scanner.nextInt();
      switch (i){
            case 3:manageSystem();
                break;
      }
    }
}


Dao层,也就是数据操作层
package main.java.com.manageSystem.dao;

import com.manageSystem.pojo.t_user;
import main.java.com.manageSystem.pojo.t_orderitem;
import main.java.com.manageSystem.pojo.t_orders;
import main.java.com.manageSystem.pojo.t_product;
import main.java.com.manageSystem.util.IdWorker;
import main.java.com.manageSystem.util.jdbcUtil;
import org.junit.Test;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class manageSystemDao {
    public static com.manageSystem.pojo.t_user findUser(String username, String password) throws Exception {
      //4.获取执行者对象
      t_user user = new t_user();
      Connection con = jdbcUtil.getCon();
      con.setTransactionIsolation(2);
      Statement stat = con.createStatement();
      //5.执行sql语句,并且接收结果
      String sql = "SELECT * FROM t_user WHERE u_name='"+username+"' and u_password='"+password+"'";
      System.out.println(sql);
      ResultSet rs = stat.executeQuery(sql);
      while (rs.next()){
            user.setuId( rs.getInt("u_id"));
            user.setuName(rs.getString("u_name"));
            user.setuPassword( rs.getString("u_password"));
            user.setuAddtime( rs.getDate("u_addtime"));
            user.setuStatus( rs.getByte("u_status"));
            user.setuEmail( rs.getString("u_email"));
            user.setuTelephone( rs.getString("u_telephone"));
            user.setuTruename( rs.getString("u_truename"));
            user.setuBirthday( rs.getDate("u_birthday"));
            user.setuActivecode=1( rs.getString("u_activecode=1"));
      return user;
      }
      jdbcUtil.close(con,stat,rs);
      return null;
    }

    public static void addGoodsOrder(String next, int i, t_user user) throws SQLException {

      //4.获取执行者对象
      Connection con = jdbcUtil.getCon();
      Statement stat = con.createStatement();
      con.setTransactionIsolation(2);
      //5.执行sql语句,并且接收结果
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
      String format = simpleDateFormat.format(new Date());//当前时间
      String uuid = UUID.randomUUID().toString();
      String substring = uuid.replace("-", "");//32位随机订单号
      String replace = substring.substring(1, substring.length() - 10);
      String s = user.getuName();//u_name
      Integer integer = user.getuId();//u_id
      String s1 = user.getuTelephone();
      String sql = "INSERT INTO t_orders(o_id,o_ordertime,o_total,o_state,o_address,o_name,o_telephone,u_id) VALUES('"+replace+"','"+format+"',(SELECT pro_price FROM t_product WHERE pro_name='"+next+"'),'1','beijing','"+next+"','"+s1+"','"+integer+"')";
      stat.execute(sql);
      System.out.println(sql);
      t_product t_product = queryProduct(next,con,stat);
      Double proPrice = t_product.getProPrice();//获得价格
      double sum=proPrice*(double) i;//总价
      Integer proId = t_product.getProId();
         uuid = uuid.substring(1, 6);
      insertOrderItem(replace,i,sum,proId,con,stat,replace);
      jdbcUtil.close(con,stat);

    }
    publicstatic voidinsertOrderItem(String replace,int i, double sum,Integer proId,Connection con,Statement stat,String integer) throws SQLException {
      //5.执行sql语句,并且接收结果
      String sql="INSERT INTO t_orderitem(o_itemid,o_count,o_subtotal,pro_id,o_id) VALUES ('"+replace+"','"+i+"','"+sum+"','"+proId+"','"+integer+"')";
      System.out.println(sql);
      stat.execute(sql);
    }
    //查询产品信息
    public static t_product queryProduct(String next,Connection con,Statement stat) throws SQLException {
      t_product t_product = new t_product();
      String sql="SELECT * FROM t_product WHERE pro_name='"+next+"'";
      System.out.println(sql);
      ResultSet rs = stat.executeQuery(sql);
      while (rs.next()){
            t_product.setcId(rs.getInt("c_id"));
            t_product.setProId( rs.getInt("pro_id"));
            t_product.setProName(rs.getString("pro_name"));
            t_product.setProPrice(rs.getDouble("pro_price"));
            t_product.setProMarketPrice(rs.getDouble("pro_market_price"));
            t_product.setProDesc(rs.getString("pro_desc"));
            t_product.setProCreate(rs.getDate("pro_create"));
            t_product.setProState(rs.getByte("pro_state"));
            t_product.setProImage(rs.getString("pro_image"));
            t_product.setProIsHot(rs.getInt("pro_is_hot"));
            return t_product;
      }
      return null;

    }

    //添加用户
    public static void addUser(String username, String password) throws SQLException {
      //4.获取执行者对象
      Connection con = jdbcUtil.getCon();
      con.setTransactionIsolation(2);
      Statement stat = con.createStatement();
      //5.执行sql语句,并且接收结果
      String sql="insert into t_user(u_name,u_password) values ('"+username+"',+'"+password+"')";
      stat.execute(sql);
      jdbcUtil.close(con,stat);
    }
//添加商品
    public static void addGoods(String name, Double price, Integer status) throws SQLException {
      //4.获取执行者对象
      IdWorker idWorker = new IdWorker();
      Long substring = idWorker.nextId();
      String id = substring.toString().substring(1, 6);
      Connection con = jdbcUtil.getCon();
      con.setTransactionIsolation(2);
      Statement stat = con.createStatement();
//      INSERT INTO t_category (c_id,c_name) VALUES ('华为')
      stat.execute("INSERT INTO t_category (c_id,c_name)values ('"+id+"','"+name+"')");
//      INSERT INTO t_product(pro_name,pro_price,pro_state,pro_create) VALUES()
      stat.execute("INSERT INTO t_product(c_id,pro_name,pro_price,pro_state,pro_create) VALUES('"+id+"','"+name+"',+'"+price+"',+'"+status+"',+'"+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())+"')");
      jdbcUtil.close(con,stat);
    }
    //查询用户的订单信息
    public static List<t_orderitem> findUserOrderItems(t_user user ) throws SQLException {
      List<t_orderitem>t_orderitems = new ArrayList<>();
      Connection con = jdbcUtil.getCon();
      con.setTransactionIsolation(2);
      Statement stat = con.createStatement();
      //5.执行sql语句,并且接收结果
      String sql = "SELECT * FROM t_orderitem WHERE o_id in(select o_id from t_orders where u_id=(select u_id from t_user where u_name='"+user.getuName()+"' and u_password ='"+user.getuPassword()+"'))";
      System.out.println(sql);
      ResultSet rs = stat.executeQuery(sql);
      while (rs.next()){
            t_orderitem t_orderitem = new t_orderitem();
            t_orderitem.setoItemid(( rs.getString("o_itemid")));
            t_orderitem.setoCount(rs.getInt("o_count"));
            t_orderitem.setoSubtotal( rs.getDouble("o_subtotal"));
            t_orderitem.setProId( rs.getInt("pro_id"));
            t_orderitem.setoId( rs.getString("o_id"));
            t_orderitems.add(t_orderitem);
      }
      jdbcUtil.close(con,stat,rs);
      return t_orderitems;
    }

    public static ArrayList<t_orders> findUserOrders(com.manageSystem.pojo.t_user user) throws SQLException {
      ArrayList<t_orders> t_orders1 = new ArrayList<>();
//      SELECT o_total,o_total,o_name FROM t_orders WHERE u_id=(SELECT u_id from t_user WHERE u_name='root' and u_password='root')
      Connection con = jdbcUtil.getCon();
      con.setTransactionIsolation(2);
      Statement stat = con.createStatement();
      //5.执行sql语句,并且接收结果
      String sql = "SELECT o_total,o_name FROM t_orders WHERE u_id=(SELECT u_id from t_user WHERE u_name='"+user.getuName()+"' and u_password='"+user.getuPassword()+"')";
         System.out.println(sql);
      ResultSet rs = stat.executeQuery(sql);
      while (rs.next()){
            t_orders t_orders = new t_orders();
            t_orderitem t_orderitem = new t_orderitem();
            t_orders.setoTotal(rs.getDouble("o_total"));
            t_orders.setoName(rs.getString("o_name"));
            t_orders1.add(t_orders);
      }
      jdbcUtil.close(con,stat,rs);
      return t_orders1;
    }
}



main层调用service层

package main.java.com.manageSystem.service;

import com.manageSystem.pojo.t_user;
import main.java.com.manageSystem.dao.manageSystemDao;
import main.java.com.manageSystem.pojo.t_orderitem;
import main.java.com.manageSystem.pojo.t_orders;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class Service {
    public static void addGoodsOrder(String next, int i, t_user user) throws SQLException {
      manageSystemDao.addGoodsOrder(next,i,user);
    }

    public static void addGoods(String name, Double price, Integer status) throws SQLException {
      manageSystemDao.addGoods(name,price,status);
    }

    public static List<t_orderitem> findUserOrderItems(t_user user) throws SQLException {
      return manageSystemDao.findUserOrderItems(user);
    }

    public static ArrayList<t_orders> findUserOrders(com.manageSystem.pojo.t_user user) throws SQLException {

      return manageSystemDao.findUserOrders(user);
    }

    public com.manageSystem.pojo.t_user findUser(String username, String password) throws Exception {
      com.manageSystem.pojo.t_user user1= manageSystemDao.findUser(username,password);
      return user1;
    }

    public void addUser(String username, String password) throws SQLException {
      manageSystemDao.addUser(username,password);
    }
}


pojo
package main.java.com.manageSystem.pojo;

import java.util.Date;

public class t_admin {
    private Integer uId;

    private String uName;

    private String uPassword;

    private Date uAddtime;

    private Byte uStatus;

    private String uEmail;

    private String uTelephone;

    public Integer getuId() {
      return uId;
    }

    public void setuId(Integer uId) {
      this.uId = uId;
    }

    public String getuName() {
      return uName;
    }

    public void setuName(String uName) {
      this.uName = uName == null ? null : uName.trim();
    }

    public String getuPassword() {
      return uPassword;
    }

    public void setuPassword(String uPassword) {
      this.uPassword = uPassword == null ? null : uPassword.trim();
    }

    public Date getuAddtime() {
      return uAddtime;
    }

    public void setuAddtime(Date uAddtime) {
      this.uAddtime = uAddtime;
    }

    public Byte getuStatus() {
      return uStatus;
    }

    public void setuStatus(Byte uStatus) {
      this.uStatus = uStatus;
    }

    public String getuEmail() {
      return uEmail;
    }

    public void setuEmail(String uEmail) {
      this.uEmail = uEmail == null ? null : uEmail.trim();
    }

    public String getuTelephone() {
      return uTelephone;
    }

    public void setuTelephone(String uTelephone) {
      this.uTelephone = uTelephone == null ? null : uTelephone.trim();
    }
}
package main.java.com.manageSystem.pojo;

public class t_category {
    private Integer cId;

    private String cName;

    public Integer getcId() {
      return cId;
    }

    public void setcId(Integer cId) {
      this.cId = cId;
    }

    public String getcName() {
      return cName;
    }

    public void setcName(String cName) {
      this.cName = cName == null ? null : cName.trim();
    }
}
package main.java.com.manageSystem.pojo;

public class t_orderitem {
    private String oItemid;

    private Integer oCount;

    private Double oSubtotal;

    private Integer proId;

    private String oId;

    public String getoItemid() {
      return oItemid;
    }

    public void setoItemid(String oItemid) {
      this.oItemid = oItemid == null ? null : oItemid.trim();
    }

    public Integer getoCount() {
      return oCount;
    }

    public void setoCount(Integer oCount) {
      this.oCount = oCount;
    }

    public Double getoSubtotal() {
      return oSubtotal;
    }

    public void setoSubtotal(Double oSubtotal) {
      this.oSubtotal = oSubtotal;
    }

    public Integer getProId() {
      return proId;
    }

    public void setProId(Integer proId) {
      this.proId = proId;
    }

    public String getoId() {
      return oId;
    }

    public void setoId(String oId) {
      this.oId = oId == null ? null : oId.trim();
    }
}
package main.java.com.manageSystem.pojo;

import java.util.Date;

public class t_orders {
    private String oId;

    private Date oOrdertime;

    private Double oTotal;

    private Integer oState;

    private String oAddress;

    private String oName;

    private String oTelephone;

    private Integer uId;

    public String getoId() {
      return oId;
    }

    public void setoId(String oId) {
      this.oId = oId == null ? null : oId.trim();
    }

    public Date getoOrdertime() {
      return oOrdertime;
    }

    public void setoOrdertime(Date oOrdertime) {
      this.oOrdertime = oOrdertime;
    }

    public Double getoTotal() {
      return oTotal;
    }

    public void setoTotal(Double oTotal) {
      this.oTotal = oTotal;
    }

    public Integer getoState() {
      return oState;
    }

    public void setoState(Integer oState) {
      this.oState = oState;
    }

    public String getoAddress() {
      return oAddress;
    }

    public void setoAddress(String oAddress) {
      this.oAddress = oAddress == null ? null : oAddress.trim();
    }

    public String getoName() {
      return oName;
    }

    public void setoName(String oName) {
      this.oName = oName == null ? null : oName.trim();
    }

    public String getoTelephone() {
      return oTelephone;
    }

    public void setoTelephone(String oTelephone) {
      this.oTelephone = oTelephone == null ? null : oTelephone.trim();
    }

    public Integer getuId() {
      return uId;
    }

    public void setuId(Integer uId) {
      this.uId = uId;
    }
}
package main.java.com.manageSystem.pojo;

import java.util.Date;

public class t_product {
    private Integer proId;

    private String proName;

    private Double proPrice;

    private Double proMarketPrice;

    private Byte proState;

    private Date proCreate;

    private Integer cId;

    private String proImage;

    private Integer proIsHot;

    private String proDesc;

    public Integer getProId() {
      return proId;
    }

    public void setProId(Integer proId) {
      this.proId = proId;
    }

    public String getProName() {
      return proName;
    }

    public void setProName(String proName) {
      this.proName = proName == null ? null : proName.trim();
    }

    public Double getProPrice() {
      return proPrice;
    }

    public void setProPrice(Double proPrice) {
      this.proPrice = proPrice;
    }

    public Double getProMarketPrice() {
      return proMarketPrice;
    }

    public void setProMarketPrice(Double proMarketPrice) {
      this.proMarketPrice = proMarketPrice;
    }

    public Byte getProState() {
      return proState;
    }

    public void setProState(Byte proState) {
      this.proState = proState;
    }

    public Date getProCreate() {
      return proCreate;
    }

    public void setProCreate(Date proCreate) {
      this.proCreate = proCreate;
    }

    public Integer getcId() {
      return cId;
    }

    public void setcId(Integer cId) {
      this.cId = cId;
    }

    public String getProImage() {
      return proImage;
    }

    public void setProImage(String proImage) {
      this.proImage = proImage == null ? null : proImage.trim();
    }

    public Integer getProIsHot() {
      return proIsHot;
    }

    public void setProIsHot(Integer proIsHot) {
      this.proIsHot = proIsHot;
    }

    public String getProDesc() {
      return proDesc;
    }

    public void setProDesc(String proDesc) {
      this.proDesc = proDesc == null ? null : proDesc.trim();
    }
}
package com.manageSystem.pojo;

import java.util.Date;

public class t_user {
    private Integer uId;

    private String uName;

    private String uPassword;

    private Date uAddtime;

    private Byte uStatus;

    private String uEmail;

    private String uTelephone;

    private String uTruename;

    private String uSex;

    private Date uBirthday;

    private String uActivecode=1;

    public Integer getuId() {
      return uId;
    }

    public void setuId(Integer uId) {
      this.uId = uId;
    }

    public String getuName() {
      return uName;
    }

    public void setuName(String uName) {
      this.uName = uName == null ? null : uName.trim();
    }

    public String getuPassword() {
      return uPassword;
    }

    public void setuPassword(String uPassword) {
      this.uPassword = uPassword == null ? null : uPassword.trim();
    }

    public Date getuAddtime() {
      return uAddtime;
    }

    public void setuAddtime(Date uAddtime) {
      this.uAddtime = uAddtime;
    }

    public Byte getuStatus() {
      return uStatus;
    }

    public void setuStatus(Byte uStatus) {
      this.uStatus = uStatus;
    }

    public String getuEmail() {
      return uEmail;
    }

    public void setuEmail(String uEmail) {
      this.uEmail = uEmail == null ? null : uEmail.trim();
    }

    public String getuTelephone() {
      return uTelephone;
    }

    public void setuTelephone(String uTelephone) {
      this.uTelephone = uTelephone == null ? null : uTelephone.trim();
    }

    public String getuTruename() {
      return uTruename;
    }

    public void setuTruename(String uTruename) {
      this.uTruename = uTruename == null ? null : uTruename.trim();
    }

    public String getuSex() {
      return uSex;
    }

    public void setuSex(String uSex) {
      this.uSex = uSex == null ? null : uSex.trim();
    }

    public Date getuBirthday() {
      return uBirthday;
    }

    public void setuBirthday(Date uBirthday) {
      this.uBirthday = uBirthday;
    }

    public String getuActivecode=1() {
      return uActivecode=1;
    }

    public void setuActivecode=1(String uActivecode=1) {
      this.uActivecode=1 = uActivecode=1 == null ? null : uActivecode=1.trim();
    }

    @Override
    public String toString() {
      return "t_user{" +
                "uId=" + uId +
                ", uName='" + uName + '\'' +
                ", uPassword='" + uPassword + '\'' +
                ", uAddtime=" + uAddtime +
                ", uStatus=" + uStatus +
                ", uEmail='" + uEmail + '\'' +
                ", uTelephone='" + uTelephone + '\'' +
                ", uTruename='" + uTruename + '\'' +
                ", uSex='" + uSex + '\'' +
                ", uBirthday=" + uBirthday +
                ", uActivecode=1='" + uActivecode=1 + '\'' +
                '}';
    }
}

相关util

package main.java.com.manageSystem.util;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;

/**
* <p>名称:IdWorker.java</p>
* <p>描述:分布式自增长ID</p>
* <pre>
*   Twitter的 Snowflake JAVA实现方案
* </pre>
* 核心代码为其IdWorker这个类实现,其原理结构如下,我分别用一个0表示一位,用—分割开部分的作用:
* 1||0---0000000000 0000000000 0000000000 0000000000 0 --- 00000 ---00000 ---000000000000
* 在上面的字符串中,第一位为未使用(实际上也可作为long的符号位),接下来的41位为毫秒级时间,
* 然后5位datacenter标识位,5位机器ID(并不算标识符,实际是为线程标识),
* 然后12位该毫秒内的当前毫秒内的计数,加起来刚好64位,为一个Long型。
* 这样的好处是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由datacenter和机器ID作区分),
* 并且效率较高,经测试,snowflake每秒能够产生26万ID左右,完全满足需要。
* <p>
* 64位ID (42(毫秒)+5(机器ID)+5(业务编码)+12(重复累加))
*
* @author Polim
*/
public class IdWorker {
    // 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动)
    private final static long twepoch = 1288834974657L;
    // 机器标识位数
    private final static long workerIdBits = 5L;
    // 数据中心标识位数
    private final static long datacenterIdBits = 5L;
    // 机器ID最大值
    private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);
    // 数据中心ID最大值
    private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
    // 毫秒内自增位
    private final static long sequenceBits = 12L;
    // 机器ID偏左移12位
    private final static long workerIdShift = sequenceBits;
    // 数据中心ID左移17位
    private final static long datacenterIdShift = sequenceBits + workerIdBits;
    // 时间毫秒左移22位
    private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;

    private final static long sequenceMask = -1L ^ (-1L << sequenceBits);
    /* 上次生产id时间戳 */
    private static long lastTimestamp = -1L;
    // 0,并发控制
    private long sequence = 0L;

    private final long workerId;
    // 数据标识id部分
    private final long datacenterId;

    public IdWorker(){
      this.datacenterId = getDatacenterId(maxDatacenterId);
      this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
    }
    /**
   * @param workerId
   *            工作机器ID
   * @param datacenterId
   *            序列号
   */
    public IdWorker(long workerId, long datacenterId) {
      if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
      }
      if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
      }
      this.workerId = workerId;
      this.datacenterId = datacenterId;
    }
    /**
   * 获取下一个ID
   *
   * @return
   */
    public synchronized long nextId() {
      long timestamp = timeGen();
      if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards.Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
      }

      if (lastTimestamp == timestamp) {
            // 当前毫秒内,则+1
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                // 当前毫秒内计数满了,则等待下一秒
                timestamp = tilNextMillis(lastTimestamp);
            }
      } else {
            sequence = 0L;
      }
      lastTimestamp = timestamp;
      // ID偏移组合生成最终的ID,并返回ID
      long nextId = ((timestamp - twepoch) << timestampLeftShift)
                | (datacenterId << datacenterIdShift)
                | (workerId << workerIdShift) | sequence;

      return nextId;
    }

    private long tilNextMillis(final long lastTimestamp) {
      long timestamp = this.timeGen();
      while (timestamp <= lastTimestamp) {
            timestamp = this.timeGen();
      }
      return timestamp;
    }

    private long timeGen() {
      return System.currentTimeMillis();
    }

    /**
   * <p>
   * 获取 maxWorkerId
   * </p>
   */
    protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
      StringBuffer mpid = new StringBuffer();
      mpid.append(datacenterId);
      String name = ManagementFactory.getRuntimeMXBean().getName();
      if (!name.isEmpty()) {
            /*
             * GET jvmPid
             */
            mpid.append(name.split("@"));
      }
      /*
         * MAC + PID 的 hashcode 获取16个低位
         */
      return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
    }

    /**
   * <p>
   * 数据标识id部分
   * </p>
   */
    protected static long getDatacenterId(long maxDatacenterId) {
      long id = 0L;
      try {
            InetAddress ip = InetAddress.getLocalHost();
            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            if (network == null) {
                id = 1L;
            } else {
                byte[] mac = network.getHardwareAddress();
                id = ((0x000000FF & (long) mac)
                        | (0x0000FF00 & (((long) mac) << 8))) >> 6;
                id = id % (maxDatacenterId + 1);
            }
      } catch (Exception e) {
            System.out.println(" getDatacenterId: " + e.getMessage());
      }
      return id;
    }

}
package main.java.com.manageSystem.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class jdbcUtil{
    //1.导入jar包
    //2.注册驱动
    static {
      try {
            Class.forName("com.mysql.jdbc.Driver");
      }
      catch (Exception e) {
      e.printStackTrace();
      }
    }
    //3.获取连接
    public static Connection getCon(){
      Connection con=null;
      try {
         con = DriverManager.getConnection("jdbc:mysql://localhost:3306/yingkongshopdb?characterEncoding=UTF-8&serverTimezone=UTC","root","root");
      }
      catch (Exception e) {
            e.printStackTrace();
      }
      returncon;
          }
          //7.释放资源
    public static   voidclose(Connection Con,Statement stat,ResultSet rs) {
      try {
      if(Con!=null){
            Con.close();
      }
      if(stat!=null){
            stat.close();
      }
      if(rs!=null){
            rs.close();
      }
      }
      catch (Exception e){
            e.printStackTrace();
      }
    }
    public static   voidclose(Connection Con,Statement stat) {
      try {
            if(Con!=null){
                Con.close();
            }
            if(stat!=null){
                stat.close();
            }
      }
      catch (Exception e){
            e.printStackTrace();
      }
    }

//
//    //6.处理结果
//      while(rs.next()) {
//      System.out.println(rs.getInt("id") + "\t" + rs.getString("name"));
//    }
//
//    //7.释放资源
//      con.close();
//      stat.close();
//      con.close();
//}
}

由于我电脑重装了,所以数据库也没了,大家自己参照pojo建一个就行,mysql连接信息也改一下.

下载地址:
**** Hidden Message *****

POJIE1123 发表于 2021-7-9 15:27

看看效果怎么样

593426276 发表于 2021-11-22 22:01

感谢,下载下来看看

mbkvpGML4 发表于 2022-2-22 09:49

感谢楼主

DzOqvIoNAW 发表于 2022-3-1 01:18

被标题吸引进来了,回复看看

mfleB 发表于 2022-3-5 10:32

感谢楼主

YVQOH0948 发表于 2022-3-8 10:31

如果楼主能每天都分享一些,那就更好了

WXRTMEJ 发表于 2022-3-8 17:10

感谢楼主

NZbn70245 发表于 2022-3-27 19:25

学习永不间断!

BurnlOvKFAPD 发表于 2022-3-27 19:30

谢谢分享
页: [1] 2 3 4 5 6 7
查看完整版本: 基于mysql的java管理系统