对象持久化操作

    技术2022-05-11  33

    对象持久化操作

    package mliwng.persistent;

    import java.sql.Connection;import java.sql.DriverManager;

    import javax.sql.DataSource;

    public class ConnectionManager {

     public static ThreadLocal local = new ThreadLocal(); private static DataSource dataSource; private static final String DRIVER = "com.mysql.jdbc.Driver"; private static final String URL = "jdbc:mysql://localhost:3306/test"; private static final String UID = "root"; private static final String PWD = "mliwng";  public static void openConnection() {  Connection conn = (Connection)local.get();    try  {   if(conn == null)   {    Class.forName(DRIVER);    conn = DriverManager.getConnection(URL,UID,PWD);    local.set(conn);   }  }catch(Exception e)  {   e.printStackTrace();  } }  public static void closeConnection() {  Connection conn = (Connection)local.get();  try  {   if(conn != null)   {    conn.close();   }  }catch(Exception e)  {   e.printStackTrace();  }finally  {   local.set(null);  } }

     public static DataSource getDataSource() {  return dataSource; }

     public static void setDataSource(DataSource dataSource) {  ConnectionManager.dataSource = dataSource; }}

    package mliwng.persistent;

    import java.lang.reflect.Field;import java.sql.Connection;import java.sql.PreparedStatement;

    public class PreparedStatementManager {

     public static PreparedStatement getSelectPstmt(Class c) {  PreparedStatement pstmt = null;  String sql = SqlManager.createSelect(c);  if(ConnectionManager.local.get()== null)  {   System.out.println("local == null");  }  try  {   pstmt = ((Connection)ConnectionManager.local.get()).prepareStatement(sql);  }catch(Exception e)  {   e.printStackTrace();  }    return pstmt; }  public static PreparedStatement getSelectByKeyPstmt(Class c,String key,Object object) {  PreparedStatement pstmt = null;  String sql = SqlManager.createSelectById(c, key);    try  {   pstmt = ((Connection)ConnectionManager.local.get()).prepareStatement(sql);   pstmt.setObject(1, object);  }catch(Exception e)  {   e.printStackTrace();  }    return pstmt; }

     public static PreparedStatement getInsertPstmt(Object object) {  PreparedStatement pstmt = null;  String sql = SqlManager.createInsert(object);    try  {    pstmt = ((Connection)ConnectionManager.local.get()).prepareStatement(sql);   setParameter(pstmt,object);  }catch(Exception e)  {   e.printStackTrace();  }    return pstmt; }  public static PreparedStatement getUpdatePstmt(Object object,String key) {  PreparedStatement pstmt = null;  String sql = SqlManager.createUpdate(object, key);    try  {   pstmt = ((Connection)ConnectionManager.local.get()).prepareStatement(sql);   int j = setParameter(pstmt,object);   Field field = object.getClass().getDeclaredField(key);   field.setAccessible(true);   System.out.println(j);   pstmt.setObject(j+1, field.get(object));     }catch(Exception e)  {   e.printStackTrace();  }    return pstmt; }  public static PreparedStatement getDeletePstmt(Class c,String key,Object object) {  PreparedStatement pstmt = null;  String sql = SqlManager.createDelete(c,key);  try  {   pstmt = ((Connection)ConnectionManager.local.get()).prepareStatement(sql);   pstmt.setObject(1,object);  }catch(Exception e)  {   e.printStackTrace();  }    return pstmt; }

     private static int setParameter(PreparedStatement pstmt,Object object) {  Class c = object.getClass();  Field[] fields = c.getDeclaredFields();    int j = 0;  for(int i = 0;i<fields.length;i++)  {   if(!isNull(fields[i],object))   {    j ++;    try    {     pstmt.setObject(j, fields[i].get(object));    }catch(Exception e)    {     e.printStackTrace();    }   }  }    return j;   }  private static boolean isNull(Field field,Object obj) {  boolean flag = true;    field.setAccessible(true);  try  {   if(field.get(obj) == null)   {    flag = true;   }else   {    flag = false;   }  }catch(Exception e)  {   e.printStackTrace();  }    return flag; }}

    package mliwng.persistent;

    import java.lang.reflect.Field;import java.sql.Connection;import java.sql.ResultSet;import java.util.ArrayList;import java.util.List;

    public class SessionManager {

     private Connection conn;  public SessionManager() {  conn = (Connection)ConnectionManager.local.get(); }  public List loadAll(Class c) throws Exception {  ResultSet rs = PreparedStatementManager.getSelectPstmt(c).executeQuery();   return this.getList(rs, c); }  public List loadByKey(Class c,String key,Object object) throws Exception {  ResultSet rs = PreparedStatementManager.getSelectByKeyPstmt(c, key,object).executeQuery();    return this.getList(rs, c); }  public int save(Object object,String key) throws Exception {  int i = 0;  i = PreparedStatementManager.getInsertPstmt(object).executeUpdate();  return i; }  public int updateByKey(Object object,String key) throws Exception {  int i = 0;  i = PreparedStatementManager.getUpdatePstmt(object, key).executeUpdate();  return i; }  public int deleteByKey(Class c,String key,Object arg) throws Exception {  int i = 0;  i = PreparedStatementManager.getDeletePstmt(c,key,arg).executeUpdate();  return i; }  private List getList(ResultSet rs,Class c) throws Exception  {  List list = new ArrayList();  Object object = null;  Field[] fields = c.getDeclaredFields();    while(rs.next())  {   object = c.newInstance();   for(int i = 0;i<fields.length;i++)   {    fields[i].setAccessible(true);    fields[i].set(object, rs.getObject(fields[i].getName()));   }      list.add(object);  }    return list; }}

    package mliwng.persistent;

    import java.lang.reflect.Field;

    public class SqlManager {

     public static String createSelect(Class c) {  StringBuffer buffer = new StringBuffer("SELECT * FROM ");  buffer.append(c.getSimpleName());    return buffer.toString(); }  public static String createSelectById(Class c , String key) {  String sql = createSelect(c);  StringBuffer buffer = new StringBuffer(sql);  buffer.append(" WHERE ");  buffer.append(key);  buffer.append(" = ?");    return buffer.toString(); }  public static String createUpdate(Object obj,String key) {  Field[] fields = obj.getClass().getDeclaredFields();  StringBuffer buffer = new StringBuffer("UPDATE ");  buffer.append(obj.getClass().getSimpleName());  buffer.append(" SET ");  for(int i = 0;i < fields.length;i ++)  {   if(!isNull(fields[i],obj))   {    buffer.append(fields[i].getName());    buffer.append( " = ? ,");   }  }  buffer = buffer.deleteCharAt(buffer.length() - 1);    buffer.append(" WHERE ");  buffer.append(key);  buffer.append(" = ?");      System.out.println(buffer.toString());  return buffer.toString(); }  public static String createInsert(Object obj) {    StringBuffer buffer = new StringBuffer("INSERT INTO ");  buffer.append(obj.getClass().getSimpleName());  buffer.append("(");  Field[] fields = obj.getClass().getDeclaredFields();  StringBuffer bufferValue = new StringBuffer();  for(int i = 0;i < fields.length;i ++)  {   if(!isNull(fields[i],obj))   {    buffer.append(fields[i].getName());    buffer.append(",");    bufferValue.append("?,");   }  }  buffer = buffer.deleteCharAt(buffer.length() - 1);  buffer.append(")");  bufferValue = bufferValue.deleteCharAt(bufferValue.length() - 1);  buffer.append(" VALUES(");  buffer.append(bufferValue);  buffer.append(")");    return buffer.toString(); }  private static boolean isNull(Field field,Object obj) {  boolean flag = true;    field.setAccessible(true);  try  {   if(field.get(obj) == null)   {    flag = true;   }else   {    flag = false;   }  }catch(Exception e)  {   e.printStackTrace();  }    return flag; }  public static String createDelete(Class c,String key) {  StringBuffer buffer = new StringBuffer("DELETE FROM ");  buffer.append(c.getSimpleName());  buffer.append(" WHERE ");  buffer.append(key);  buffer.append(" = ?");  return buffer.toString(); } }

    package mliwng.persistent;

    import java.sql.Connection;

    public class TransactionManager {  public static void beginTransaction() {  Connection conn = (Connection)ConnectionManager.local.get();  try  {   conn.setAutoCommit(false);  }catch(Exception e)  {   e.printStackTrace();  } }  public static void commit() {  Connection conn = (Connection)ConnectionManager.local.get();  try  {   conn.commit();  }catch(Exception e)  {   e.printStackTrace();  } }  public static void rollback() {  Connection conn = (Connection)ConnectionManager.local.get();  try  {   conn.rollback();  }catch(Exception e)  {   e.printStackTrace();  } }}

     

    这个是测试用的package test;

    public class User{ private Integer id; private String userName; private String userPassword;  public Integer getId() {  return id; } public void setId(Integer id) {  this.id = id; } public String getUserName() {  return userName; } public void setUserName(String userName) {  this.userName = userName; } public String getUserPassword() {  return userPassword; } public void setUserPassword(String userPassword) {  this.userPassword = userPassword; }}

    package test;

    import java.sql.Connection;import java.sql.ResultSet;import java.sql.Statement;import java.util.List;

    import mliwng.persistent.ConnectionManager;import mliwng.persistent.SessionManager;import mliwng.persistent.TransactionManager;

    public class UserDao{

     public List list() throws Exception  {  return new SessionManager().loadAll(User.class); }  public void insert(User user) throws Exception {  new SessionManager().save(user, "id"); }  public void update(User user) throws Exception {  new SessionManager().updateByKey(user, "id"); }  public void delete(int id) throws Exception {  new SessionManager().deleteByKey(User.class,"id",id); }  public List select() throws Exception {  return new SessionManager().loadByKey(User.class, "userName","mliwng"); }

     public static void main(String[] args) {  UserDao dao = new UserDao();    User user = new User();  user.setUserName("11111");  user.setId(1);     User user1 = new User();  user1.setUserName("cccc");  user1.setUserPassword("cccc");    User user2 = new User();  user2.setUserName("bbbb");  user2.setUserPassword("bbb");    ConnectionManager.openConnection();    //打开连接  TransactionManager.beginTransaction(); //开启事务  try  {   dao.insert(user2); //调用UserDao.insert()方法保存User2对象   TransactionManager.commit();  提交事务  }catch(Exception e)  {   e.printStackTrace();   TransactionManager.rollback();   //出错时回滚  }finally  {   ConnectionManager.closeConnection();  } }} 


    最新回复(0)