commit fe9e8b1482eda5d80e461c4d56d142d48b0ad7bf Author: yaclty Date: Wed Dec 23 16:51:59 2020 +0800 init diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..46c465b --- /dev/null +++ b/.classpath @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..41ad661 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.DS_Store +*.bak +bin + diff --git a/.project b/.project new file mode 100644 index 0000000..e1449b4 --- /dev/null +++ b/.project @@ -0,0 +1,17 @@ + + + Book + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..7341ab1 --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.7 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.7 diff --git a/src/Application.java b/src/Application.java new file mode 100644 index 0000000..247f175 --- /dev/null +++ b/src/Application.java @@ -0,0 +1,70 @@ +import java.sql.SQLException; +import java.util.List; + +import bean.Book; +import utils.DbUtil; +import utils.system; + +public class Application { + private DbUtil db = DbUtil.createDBUtil(); + + public static void main(String[] args) { + new Application().run(); + } + private void run() { + System.out.println("欢迎使用图书管理系统 "); + System.out.println("\t v1.0.0"); + System.out.println("--------系统菜单---------"); + System.out.println(" 1.检索全部图书"); + System.out.println(" 2.根据编号查询图书"); + System.out.println(" 3.添加图书"); + System.out.println(" 4.修改图书信息"); + System.out.println(" 5.删除图书"); + System.out.println(" 6.退出系统"); + System.out.println("--------------------------"); + try { + int input = Integer.parseInt(system.input("请选择要进行的操作编号:")); // 获取输入 + if (input == 1) { + // 全部 + showAllBook(); + } +// else if (input == 2) { +// // 根据编号查询 +// queryBook(); +// } else if (input == 3) { +// // 添加 +// addBook(); +// } else if (input == 4) { +// modifyBook();// 修改 +// } else if (input == 5) { +// removeBook(); // 删除 +// } + else if (input == 6) { + System.out.println("已经退出系统了"); + return; // 推出递归 + } else { + System.err.println("选择错误"); + } + run(); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + private void showAllBook() throws SQLException { + + if (db.count("book") == 0) { + system.error("还没有入库任何图书"); + return; + } + system.println("编号\t图书名称\t作者\t价格\t出版社"); + List list = db.queryList(Book.class); + for (Book book : list) { + system.println(book.getId(), '\t', book.getName(), '\t', book.getAuthor().getName(), '\t', book.getPrice(), + '\t', book.getPublisher().getName()); + } + } + + +} diff --git a/src/bean/Author.java b/src/bean/Author.java new file mode 100644 index 0000000..9f76147 --- /dev/null +++ b/src/bean/Author.java @@ -0,0 +1,50 @@ +package bean; + +import utils.Table; +import utils.TableField; + +@Table(name = "author") +public class Author extends BaseModel { + @TableField(pk = true, autoIncrement = true) + private int id; + @TableField() + private String name; + + public Author() { + super(); + } + + public Author(int id, String name) { + super(); + this.id = id; + this.name = name; + } + + public Author(String name) { + super(); + this.name = name; + } + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + // TODO Auto-generated method stub + return this.id + "@" + this.name; + } +} diff --git a/src/bean/BaseModel.java b/src/bean/BaseModel.java new file mode 100644 index 0000000..8c34503 --- /dev/null +++ b/src/bean/BaseModel.java @@ -0,0 +1,33 @@ +package bean; + +import java.util.Date; + +import utils.TableField; + +public class BaseModel { + @TableField(name="create_time") + protected Date createTime; + @TableField(name="update_time") + protected Date updateTime; + protected short status; + + public Date getCreateTime() { + return createTime; + } + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + public Date getUpdateTime() { + return updateTime; + } + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + public short getStatus() { + return status; + } + public void setStatus(short status) { + this.status = status; + } + +} diff --git a/src/bean/Book.java b/src/bean/Book.java new file mode 100644 index 0000000..1a2093a --- /dev/null +++ b/src/bean/Book.java @@ -0,0 +1,52 @@ +package bean; + +import utils.TableField; +import utils.Table; + +@Table(name = "book") +public class Book extends BaseModel { + + @TableField() + private int id; + @TableField() + private String name; + @TableField() + private Author author; + @TableField() + private Publisher publisher; + @TableField() + private float price; + + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public Author getAuthor() { + return author; + } + public void setAuthor(Author author) { + this.author = author; + } + public Publisher getPublisher() { + return publisher; + } + public void setPublisher(Publisher publisher) { + this.publisher = publisher; + } + public float getPrice() { + return price; + } + public void setPrice(float price) { + this.price = price; + } + + +} diff --git a/src/bean/Publisher.java b/src/bean/Publisher.java new file mode 100644 index 0000000..293cbf2 --- /dev/null +++ b/src/bean/Publisher.java @@ -0,0 +1,24 @@ +package bean; + +import utils.TableField; +import utils.Table; + +@Table(name = "publisher") +public class Publisher extends BaseModel { + @TableField() + private int id; + @TableField() + private String name; + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } +} diff --git a/src/jars/c3p0-0.9.2-sources.jar b/src/jars/c3p0-0.9.2-sources.jar new file mode 100644 index 0000000..1e45ed0 Binary files /dev/null and b/src/jars/c3p0-0.9.2-sources.jar differ diff --git a/src/jars/commons-dbutils-1.6-src.zip b/src/jars/commons-dbutils-1.6-src.zip new file mode 100644 index 0000000..13aa012 Binary files /dev/null and b/src/jars/commons-dbutils-1.6-src.zip differ diff --git a/src/jars/mysql-connector-java-5.1.37.jar b/src/jars/mysql-connector-java-5.1.37.jar new file mode 100644 index 0000000..7a19168 Binary files /dev/null and b/src/jars/mysql-connector-java-5.1.37.jar differ diff --git a/src/jars/t.sql b/src/jars/t.sql new file mode 100644 index 0000000..6251751 --- /dev/null +++ b/src/jars/t.sql @@ -0,0 +1,29 @@ +DROP TABLE IF EXISTS author; +CREATE TABLE author( + id INT(10) PRIMARY KEY AUTO_INCREMENT, + NAME VARCHAR(10) NOT NULL, + create_time DATETIME, + update_time DATETIME, + STATUS TINYINT(2) DEFAULT 1 +); +DROP TABLE IF EXISTS publisher; +CREATE TABLE publisher( + id INT(10) PRIMARY KEY AUTO_INCREMENT, + NAME VARCHAR(10) NOT NULL, + create_time DATETIME, + update_time DATETIME, + STATUS TINYINT(2) DEFAULT 1 +); +DROP TABLE IF EXISTS book; +CREATE TABLE book( + id INT(10) PRIMARY KEY AUTO_INCREMENT, + NAME VARCHAR(10) NOT NULL, + author INT(10) REFERENCES author(id), + publisher INT(10) REFERENCES publisher(id), + price DECIMAL(10,2) NOT NULL, + create_time DATETIME, + update_time DATETIME, + STATUS TINYINT(2) DEFAULT 1 +); + +INSERT INTO `books`.`author`(`id`,`name`,`create_time`,`update_time`,`status`) VALUES ( NULL,'zhangsan','2020-12-22','2020-12-22','1') diff --git a/src/test/DbUtilTest.java b/src/test/DbUtilTest.java new file mode 100644 index 0000000..8d476ab --- /dev/null +++ b/src/test/DbUtilTest.java @@ -0,0 +1,61 @@ +package test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.lang.reflect.Field; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + +import bean.Author; +import utils.DbUtil; + +public class DbUtilTest { + DbUtil db = DbUtil.createDBUtil(); + @Test + public void testGetModel() throws Exception { + Map fs = db.getModel("bean.Book"); + Assert.assertEquals("price", fs.get("price")); + Assert.assertEquals("update_time", fs.get("updateTime")); + } + + @Test + public void testAuthor() throws Exception { + Author t = db.get(Author.class, "select * from author where id = ?",1); +// assertNotNull(t); + if(t != null) { + assertEquals(1, t.getId()); + System.out.println(t); + } + List list = db.queryList(Author.class, "select * from author limit 1"); + assertEquals(1, list.size()); + } + + @Test + public void testAddAuthor() throws SQLException { + int ret = db.save("insert into author (name,create_time,update_time) values (?,now(),now())","lisi"); + assertEquals(1, ret); + } + + + + public static void main(String[] args) throws Exception { +// testGetModel(); + + Class cls = Author.class; + List fs = new ArrayList(); + fs.addAll(Arrays.asList(cls.getDeclaredFields())); + Class parent = cls.getSuperclass(); + if (parent.getName().equalsIgnoreCase("bean.BaseModel")) { + fs.addAll(Arrays.asList(parent.getDeclaredFields())); + } + for (Field f : fs) { + System.out.println(f.getName()); + } + } +} diff --git a/src/utils/BeanProperty.java b/src/utils/BeanProperty.java new file mode 100644 index 0000000..3ad4be7 --- /dev/null +++ b/src/utils/BeanProperty.java @@ -0,0 +1,55 @@ +package utils; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + +public class BeanProperty { + public String name; + public String field; + public String type; + public String pk = null; + public boolean autoIncrement = false; + public boolean fromSuper = false; + + public BeanProperty() { + } + + public BeanProperty(String name, String field, String type) { + this.name = name; + this.field = field; + this.type = type; + } + + public BeanProperty(String name, String field, String type, boolean fromSuper) { + this.name = name; + this.field = field; + this.type = type; + this.fromSuper = fromSuper; + } + + public static List getProperties(String className) throws ClassNotFoundException { + List map = new ArrayList(); + Class cls = Class.forName(className); + + Class parent = cls.getSuperclass(); + parseFields(cls.getDeclaredFields(), map, false); + + if (parent.getName().equalsIgnoreCase("bean.BaseModel")) { + parseFields(parent.getDeclaredFields(), map, true); + } + return map; + } + + private static void parseFields(Field[] fs, List map, boolean fromSuper) { + for (Field f : fs) { + TableField tf = f.getAnnotation(TableField.class); + if (tf != null) { + BeanProperty bp = new BeanProperty(f.getName(), "".equals(tf.name()) ? f.getName() : tf.name(), + f.getType().getName(), fromSuper); + bp.pk = tf.relationKey(); + map.add(bp); + } + } + } +} diff --git a/src/utils/DbUtil.java b/src/utils/DbUtil.java new file mode 100644 index 0000000..68d9c91 --- /dev/null +++ b/src/utils/DbUtil.java @@ -0,0 +1,246 @@ +package utils; + +import java.lang.reflect.Field; +import java.sql.Connection; +import java.sql.Date; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class DbUtil { + static { + try { + Class.forName("com.mysql.jdbc.Driver"); + } catch (ClassNotFoundException e) { + System.err.println("加载驱动失败:" + e.getMessage()); + } + } + + private static Connection conn; + private PreparedStatement ps; + private ResultSet rs; +// private static DbUtil dbUtil = null; + + public static DbUtil createDBUtil() { + return createDBUtil("jdbc:mysql://127.0.0.1:3306/books", "root", "123456"); + } + + public static DbUtil createDBUtil(String url, String user, String pwd) { +// if (dbUtil == null) { +// dbUtil =; +// } + return new DbUtil(url, user, pwd); + } + + private DbUtil(String url, String user, String pwd) { + try { + conn = DriverManager.getConnection(url, user, pwd); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + public Map getModel(String className) throws ClassNotFoundException { + Map map = new HashMap(); + Class cls = Class.forName(className); + + Class parent = cls.getSuperclass(); + List fs = new ArrayList(); + fs.addAll(Arrays.asList(cls.getDeclaredFields())); + if (parent.getName().equalsIgnoreCase("bean.BaseModel")) { + fs.addAll(Arrays.asList(parent.getDeclaredFields())); + } + for (Field f : fs) { + TableField tf = f.getAnnotation(TableField.class); + if (tf != null) { + map.put(f.getName(), "".equals(tf.name()) ? f.getName() : tf.name()); + } + } + return map; + } + + public void dispose() { + dispose(false); + } + + public void dispose(boolean closeConnection) { + if (null != rs) { + try { + rs.close(); + this.rs = null; + } catch (SQLException e) { + e.printStackTrace(); + } + } + if (null != ps) { + try { + ps.close(); + this.ps = null; + } catch (SQLException e) { + e.printStackTrace(); + } + } + if (closeConnection) { + if (null != conn) { + try { + conn.close(); + conn = null; + } catch (SQLException e) { + e.printStackTrace(); + } + } + } + } + + public int save(String sql, Object... params) throws SQLException { + prepareStatement(sql, params); + int count = ps.executeUpdate(); + this.dispose(); + return count; + } + + private void prepareStatement(String sql, Object... params) throws SQLException { + ps = conn.prepareStatement(sql); + if (params.length > 0) { + for (int i = 0; i < params.length; i++) { + ps.setObject(i + 1, params[i]); + } + } + } + + private void executeQuery(String sql, Object... params) throws SQLException { + prepareStatement(sql, params); + rs = ps.executeQuery(); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public T get(Class cls, String sql, Object... params) throws SQLException { + executeQuery(sql, params); + T t = null; + if (rs.next()) { + t = (T) convertToBean(cls); + } + this.dispose(); + return t; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public List queryList(Class cls, String sql, Object... params) throws SQLException { + executeQuery(sql, params); + List ts = new ArrayList(); + while (rs.next()) { + ts.add((T) convertToBean(cls)); + } + this.dispose(); + return ts; + } + + @SuppressWarnings("unused") + private boolean inArray(String[] arr, String str) { + for (String s : arr) { + if (str.equalsIgnoreCase(s)) { + return true; + } + } + return false; + + } + +// private static SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + @SuppressWarnings("unused") + private boolean isDBNull(ResultSet rs,String key) { + return true; + } + private Object getValueFromResult(BeanProperty p, Field f, T t) throws SQLException, ClassNotFoundException { +// String[] basicType = { "int", "float", "short", "long", "java.lang.String" }; + String type = p.type.toLowerCase(); + if (type.equals("int")) { // 基本类型 + return rs.getInt(p.field); + }else if (type.equals("float")) { // 基本类型 + return rs.getFloat(p.field); + }else if (type.equals("double")) { // 基本类型 + return rs.getDouble(p.field); + }else if (type.equals("short")) { // 基本类型 + return rs.getShort(p.field); + }else if (type.equals("long")) { // 基本类型 + return rs.getLong(p.field); + }else if (type.equals("java.lang.string")) { // 基本类型 + return rs.getString(p.field); + } else if (type.equals("java.util.date")) { // 日期类型 + Object v = rs.getObject(p.field); + if(null == v) return null; + return new Date(rs.getDate(p.field).getTime()); + } else { + String pk = p.pk; + if (null == p.pk || "".equals(p.pk)) { + pk = "id"; + } + Class cls = Class.forName(p.type); + Table table = cls.getAnnotation(Table.class); + if(table == null) return null; + String tableName = table.name(); + if (tableName == null || "".equals(tableName)) { + tableName = cls.getSimpleName(); + } + return createDBUtil().get(cls, "select * from " + tableName + " where " + pk + "=?", rs.getObject(p.field)); + } + } + + private T convertToBean(Class cls) throws SQLException { + String name = cls.getName(); + T t = null; + try { + t = (T) cls.newInstance(); + List props = BeanProperty.getProperties(name); + Class parent = cls.getSuperclass(); + for (BeanProperty p : props) { + Field f = p.fromSuper ? parent.getDeclaredField(p.name) : cls.getDeclaredField(p.name); + f.setAccessible(true); + f.set(t, getValueFromResult(p, f, t)); + } + } catch (ClassNotFoundException e) { + throw new SQLException("ClassNotFoundException:" + name); + } catch (NoSuchFieldException e) { + throw new SQLException("转换实体失败(没有找到对应字段 " + e.getMessage() + ")"); + } catch (SecurityException e) { + throw new SQLException("SecurityException:" + e.getMessage()); + } catch (IllegalArgumentException e) { + throw new SQLException("IllegalArgumentException:" + e.getMessage()); + } catch (IllegalAccessException e) { + throw new SQLException("IllegalAccessException:" + e.getMessage()); + } catch (InstantiationException e) { + throw new SQLException("InstantiationException:" + e.getMessage()); + } + return t; + } + + public int count(String tableName) { + int count = 0; + try { + executeQuery("select count(*) as total_count from " + tableName); + if (rs.next()) { + count = rs.getInt(1); + } + } catch (SQLException e) { + e.printStackTrace(); + } finally { + this.dispose(); + } + return count; + } + + public List queryList(Class cls) throws SQLException { + String tableName = cls.getAnnotation(Table.class).name(); + if (tableName == null || "".equals(tableName)) { + tableName = cls.getSimpleName(); + } + return queryList(cls, "select * from " + tableName); + } +} diff --git a/src/utils/Table.java b/src/utils/Table.java new file mode 100644 index 0000000..9d00d6e --- /dev/null +++ b/src/utils/Table.java @@ -0,0 +1,12 @@ +package utils; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface Table { + public String name(); +} diff --git a/src/utils/TableField.java b/src/utils/TableField.java new file mode 100644 index 0000000..1654516 --- /dev/null +++ b/src/utils/TableField.java @@ -0,0 +1,18 @@ +package utils; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface TableField { + public String name() default ""; + public String relationKey() default ""; + public boolean pk() default false; + public boolean autoIncrement() default false; +// public Class reference(); +} diff --git a/src/utils/system.java b/src/utils/system.java new file mode 100644 index 0000000..1df5460 --- /dev/null +++ b/src/utils/system.java @@ -0,0 +1,33 @@ +package utils; + +import java.util.Scanner; + +public class system { + private static String parseMessage(Object... params) { + StringBuilder sb = new StringBuilder(); + for (Object o : params) { + sb.append(o); + } + return sb.toString(); + } + + public static void println(Object... params) { + System.out.println(parseMessage(params)); + } + + public static void error(Object... params) { + System.err.println(parseMessage(params)); + } + + public static String input() { + return input(null); + } + + public static String input(String msg) { + if (null != msg) { + System.out.print(msg); + } + Scanner s = new Scanner(System.in); + return s.nextLine(); + } +}