自动生成mybatis连接的数据库三件套文件mapper.java/mapper.xml/bean.java
bean自动生成
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;
public class BeanCreater {
private Connection connection;
private PreparedStatement UserQuery;
/*mysql url的连接字符串*/
private Vector<String> vector = new Vector<String>();
//数据库的列名称
private String[] colnames; // 列名数组
//列名类型数组
private String[] colTypes;
public BeanCreater(){
connection = Util.getConnection();
}
public void doAction(){
ResultSetMetaData metadata = Util.getCols();
//数据库的字段个数
int len;
try {
len = metadata.getColumnCount();
//字段名称
colnames = new String[len+1];
//字段类型 --->已经转化为java中的类名称了
colTypes = new String[len+1];
for(int i= 1;i<=len;i++){
colnames[i] = metadata.getColumnName(i); //获取字段名称
colTypes[i] = Util.sqlType2JavaType(metadata.getColumnTypeName(i)); //获取字段类型
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public StringBuffer getClassStr(){
//输出的类字符串
StringBuffer str = new StringBuffer("");
//获取表类型和表名的字段名
this.doAction();
//校验
if(null == colnames && null == colTypes) return null;
//拼接
str.append("public class "+GetTuoFeng(Util.getTableName())+" {\r\n");
//拼接属性
for(int index=1; index < colnames.length ; index++){
str.append(getAttrbuteString(colnames[index],colTypes[index]));
}
//拼接get,Set方法
for(int index=1; index < colnames.length ; index++){
str.append(getGetMethodString(colnames[index],colTypes[index]));
str.append(getSetMethodString(colnames[index],colTypes[index]));
}
str.append("}\r\n");
//输出到文件中
//File file = new File("E:/mengwx/【源码】mysql版本_spring4.0/FHMYSQL/src/com/fh/entity/"+GetTuoFeng(table)+".java");
//BufferedWriter write = null;
/*try {
write = new BufferedWriter(new FileWriter(file));
write.write(str.toString());
write.close();
} catch (IOException e) {
e.printStackTrace();
if (write != null)
try {
write.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} */
return str;
}
/*
* 获取字段字符串*/
public StringBuffer getAttrbuteString(String name, String type) {
if(!check(name,type)) {
System.out.println("类中有属性或者类型为空");
return null;
};
String format = String.format(" private %s %s;\n\r", new String[]{type,name});
return new StringBuffer(format);
}
/*
* 校验name和type是否合法*/
public boolean check(String name, String type) {
if("".equals(name) || name == null || name.trim().length() ==0){
return false;
}
if("".equals(type) || type == null || type.trim().length() ==0){
return false;
}
return true;
}
/*
* 获取get方法字符串*/
private StringBuffer getGetMethodString(String name, String type) {
if(!check(name,type)) {
System.out.println("类中有属性或者类型为空");
return null;
};
String Methodname = "get"+GetTuoFeng(name);
String format = String.format(" public %s %s(){\n\r", new Object[]{type,Methodname});
format += String.format(" return this.%s;\r\n", new Object[]{name});
format += " }\r\n";
return new StringBuffer(format);
}
//将名称首字符大写
private String GetTuoFeng(String name) {
name = name.trim();
if(name.length() > 1){
name = Util.getTypeName(name);
}else
{
name = name.toUpperCase();
}
return name;
}
/*
* 获取字段的get方法字符串*/
private Object getSetMethodString(String name, String type) {
if(!check(name,type)) {
System.out.println("类中有属性或者类型为空");
return null;
};
String Methodname = "set"+GetTuoFeng(name);
String format = String.format(" public void %s(%s %s){\n\r", new Object[]{Methodname,type,name});
format += String.format(" this.%s = %s;\r\n", new Object[]{name,name});
format += " }\r\n";
return new StringBuffer(format);
}
public static void main(String[] args) {
BeanCreater bean = new BeanCreater();
System.err.println(bean.getClassStr());
}
}
mapper.xml生成
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class MapperCreater {
public static String createMapperString(String tableName) {
String paramTemplate = " <result property=\"##col_name##\" column=\"##col_name##\" javaType=\"java.lang.##col_type##\"></result>\r\n";
String template = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +
"<!DOCTYPE mapper PUBLIC \"-//mybatis.org/DTD Mapper 3.0\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\r\n" +
"<mapper namespace=\"pers.bertram.mappers.##class_name##Mapper\">\r\n" +
"<!-- 自定义返回结果集 -->\r\n" +
" <resultMap id=\"##type_id##\" type=\"##class_name##\">\r\n" +
" ##params##\r\n" +
" </resultMap>\r\n" +
"<!-- 在各种标签中的id属性必须和接口中的方法名相同 , id属性值必须是唯一的,不能够重复使用。parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型--> \r\n" +
"<!-- useGeneratedKeys:( 仅 对 insert 有 用 ) 这 会 告 诉 MyBatis 使 用 JDBC 的getGeneratedKeys \r\n" +
" 方法来取出由数据(比如:像 MySQL 和 SQLServer 这样的数据库管理系统的自动递增字段)内部生成的主键。默认值: false。 --> \r\n" +
"<!--keyProperty: (仅对 insert有用)标记一个属性, MyBatis 会通过 getGeneratedKeys或者通过 insert 语句的 selectKey 子元素设置它的值。默认:不设置。 -->\r\n" +
"<!--#{}中的内容,为占位符,当参数为某个JavaBean时,表示放置该Bean对象的属性值 -->\r\n" +
"\r\n" +
"\r\n" +
" <insert id=\"insert##class_name##\" useGeneratedKeys=\"true\" keyProperty=\"##main_key##\">\r\n" +
" insert into ##table_name## (##insert_params##) values (##insert_values##)\r\n" +
" </insert>\r\n" +
" \r\n" +
" <update id=\"update##class_name##\" >\r\n" +
" update ##table_name## set ##update_params## where ##main_key##=#{##main_key##}\r\n" +
" </update>\r\n" +
" \r\n" +
" <delete id=\"delete##class_name##\" parameterType=\"int\">\r\n" +
" delete from ##table_name## where ##main_key##=#{##main_key##} \r\n" +
" </delete>\r\n" +
" \r\n" +
" <select id=\"select##class_name##ById\" parameterType=\"int\" resultMap=\"##type_id##\">\r\n" +
" select * from ##table_name## where ##main_key##=#{##main_key##}\r\n" +
" </select>\r\n" +
" \r\n" +
" <select id=\"selectAll##class_name##\" resultMap=\"##type_id##\">\r\n" +
" select * from ##table_name##\r\n" +
" </select>\r\n" +
" \r\n" +
" \r\n" +
"</mapper>\r\n";
String insert_params = "";
String insert_values = "";
String update_params = "";
String params = "";
ResultSetMetaData metadata = Util.getCols();
//数据库的字段个数
try {
//字段名称
for(int i = 1; i <= metadata.getColumnCount(); i++){
String colName = metadata.getColumnName(i);
String colType = Util.sqlType2JavaType(metadata.getColumnTypeName(i));
params += paramTemplate.replaceAll("##col_name##", colName)
.replaceAll("##col_type##", colType);
insert_params += ", " + colName;
insert_values += ", " + "#{##c##}".replace("##c##", colName);
update_params += ", " + colName + " = " + "#{##c##}".replace("##c##", colName);
}
insert_params = insert_params.substring(2);
insert_values = insert_values.substring(2);
update_params = update_params.substring(2);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
template = template.replaceAll("##table_name##", tableName)
.replaceAll("##type_id##", tableName.replaceAll("_", ""))
.replaceAll("##class_name##", Util.getTypeName(tableName))
.replaceAll("##main_key##", "video_id")
.replaceAll("##params##", params)
.replaceAll("##insert_params##", insert_params)
.replaceAll("##insert_values##", insert_values)
.replaceAll("##update_params##", update_params);
return template.replaceAll("java.lang.int", "java.lang.Integer")
.replaceAll("java.lang.double", "java.lang.Double")
.replaceAll("java.lang.Date", "java.sql.Date");
}
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("d:\\" + Util.getTypeName(Util.getTableName()) + "Mapper.xml"), "UTF-8"));
bw.write(createMapperString(Util.getTableName()));
bw.flush();
bw.close();
}
}
mapper.java生成
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class MapperJava {
public static void main(String[] args) throws IOException {
System.out.println(createMapperString(Util.getTableName()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("d:\\\\" + Util.getTypeName(Util.getTableName()) + "Mapper.java"), "UTF-8"));
bw.write(createMapperString(Util.getTableName()));
bw.flush();
bw.close();
}
private static String createMapperString(String tableName) {
String template = "package pers.bertram.mappers;\r\n" +
"\r\n" +
"import java.util.List;\r\n" +
"\r\n" +
"import pers.bertram.beans.##class_name##;\r\n" +
"\r\n" +
"\r\n" +
"public interface ##class_name##Mapper {\r\n" +
" /**\r\n" +
" * 新增用\r\n" +
" * @param user\r\n" +
" * @return\r\n" +
" * @throws Exception\r\n" +
" */\r\n" +
" public int insert##class_name##(##class_name## ##type_id##) throws Exception;\r\n" +
" /**\r\n" +
" * 修改用\r\n" +
" * @param user\r\n" +
" * @param id\r\n" +
" * @return\r\n" +
" * @throws Exception\r\n" +
" */\r\n" +
" public int update##class_name## (##class_name## ##type_id##,int ##main_key##) throws Exception;\r\n" +
" /**\r\n" +
" * 除用\r\n" +
" * @param id\r\n" +
" * @return\r\n" +
" * @throws Exception\r\n" +
" */\r\n" +
" public int delete##class_name##(int ##main_key##) throws Exception;\r\n" +
" /**\r\n" +
" * 根据id查询用户信息\r\n" +
" * @param id\r\n" +
" * @return\r\n" +
" * @throws Exception\r\n" +
" */\r\n" +
" public ##class_name## select##class_name##ById(int ##main_key##) throws Exception;\r\n" +
" /**\r\n" +
" * 查询所有的用户信息\r\n" +
" * @return\r\n" +
" * @throws Exception\r\n" +
" */\r\n" +
" public List<##class_name##> selectAll##class_name##() throws Exception;\r\n" +
"}\r\n";
template = template.replaceAll("##table_name##", tableName)
.replaceAll("##type_id##", tableName.replaceAll("_", ""))
.replaceAll("##class_name##", Util.getTypeName(tableName))
.replaceAll("##main_key##", "video_id");
return template;
}
}
Util工具库
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class Util {
//mysql jdbc的java包驱动字符串
private static String driverClassName = "com.mysql.jdbc.Driver";
//数据库中的表名
private static String table = "video";
private static String url = "jdbc:mysql://127.0.0.1:3306/videos?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false";
//账号
private static String user = "root";
//密码
private static String password = "admin";
public static String getTableName() {
return table;
}
public static Connection getConnection() {
Connection connection = null;
try {//驱动注册
Class.forName(driverClassName);
if (connection == null || connection.isClosed())
//获得链接
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
System.out.println("Oh,not");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Oh,not");
}
return connection;
}
/*
mysql的字段类型转化为java的类型*/
public static String sqlType2JavaType(String sqlType) {
if(sqlType.equalsIgnoreCase("bit")){
return "boolean";
}else if(sqlType.equalsIgnoreCase("tinyint")){
return "byte";
}else if(sqlType.equalsIgnoreCase("smallint")){
return "short";
}else if(sqlType.equalsIgnoreCase("int")){
return "int";
}else if(sqlType.equalsIgnoreCase("bigint")){
return "long";
}else if(sqlType.equalsIgnoreCase("float")){
return "float";
}else if(sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric")
|| sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money")
|| sqlType.equalsIgnoreCase("smallmoney") || sqlType.equalsIgnoreCase("double")){
return "double";
}else if(sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")
|| sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")
|| sqlType.equalsIgnoreCase("text")){
return "String";
}else if(sqlType.equalsIgnoreCase("datetime") ||sqlType.equalsIgnoreCase("date")){
return "Date";
}else if(sqlType.equalsIgnoreCase("image")){
return "Blod";
}else if(sqlType.equalsIgnoreCase("timestamp")){
return "Timestamp";
}
return "Unknown Type " + sqlType;
}
public static String getTypeName(String name) {
name = name.substring(0, 1).toUpperCase()+name.substring(1);
String r = "";
for (int i = 0; i < name.length(); i++) {
if (name.charAt(i) == '_') {
r += ("" + name.charAt(++i)).toUpperCase();
continue;
}
r += name.charAt(i);
}
return r;
}
public static ResultSetMetaData getCols() {
String sql = "select * from "+ Util.getTableName();
try {
PreparedStatement statement = Util.getConnection().prepareStatement(sql);
//获取数据库的元数据
ResultSetMetaData metadata = statement.getMetaData();
return metadata;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static String ToMultiLines(String filePath) throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"gb2312"));
String line = "";
StringBuilder sb = new StringBuilder();
while((line = reader.readLine()) != null) {
line = line.replaceAll("\"", "\\\\\"");
sb.append("\"" + line + "\\r\\n\" + \n");
}
return sb.toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (reader != null) reader.close();
}
return "error";
}
}