類比實現ORM架構

來源:互聯網
上載者:User
1 定義對應檔的XML格式。

//Students.xml<?xml version="1.0"?><mapping><class name="User" table="user"><property name="id" column="id"><property name="name" column="name">         </class></mapping>

2. 擷取XML中的值

把XML中class節點下的table賦值給tableName,把XML中property節點下的name和column放入Map類型的集合中。

//屬性--欄位<屬性,欄位>private Map<String,String> maps=new HashMap<String,String>();private String tableName;private String[] methodName;public Session() throws Exception{SAXReader reader=new SAXReader();File f=new File("Students.xml");Document doc=reader.read(f);Element root=doc.getRootElement();List list1=root.elements();for(int i=0;i<list1.size();i++){Element node1=list1.get(i);tableName=node1.attributeValue("table");List list2=node1.elements();for(int j=0;j<list2.size();j++){Element node2=(Element)list2.get(j);map.put(node2.attributeValue("name"),node2.attributeValue("column"));}methodNames=new String[map.size()];}

3. 產生prepareStatement需要的sql指令碼,insert into 表名(欄位1,欄位2……)values(?,?……);

由insert語句模板,產生具體的sql指令碼,如【insert into students(id,name)values(?,?);】,同時根據name構造getter方法。

實現方法:1,從xml檔案

private String createSQL(){String s1="";String s2="";for(String key:maps.keySet()){String value=maps.get(key);s1+=value+",";methodName[index++]="get"+Character.toUpperCase(key.charAt(0))+key.substring(1);}s1=s1.substring(0,s1.length()-1);for(int i=0;i<maps.size();i++){s2+="?,";}s2=s2.substring(0,s1.length()-1);String sql="insert into "+tableName+"("+s1+")value("+s2+");"}}
4. 利用反射,構造save方法。

1,建立insert的sql模板;2,建立資料庫連接,擷取prepareStatement對象;3,用反射調用傳入對象的getter方法,擷取對象的值;4,把擷取的值利用setType傳給prepareStatement;5,執行prepareStatement,關閉資源。

public void save(Students stu) throws Exception{String sql=creatSQL();//建立插入SQL語句模板System.out.println(sql);//列印sql語句//建立資料庫連接,執行sql語句Connection conn=null;PreparedStatement stmt=nullClass.forName("com.mysql.jdbc.Driver");conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test");stmt=conn.prepareStatement(sql);for(int i=0;i<methodNames.length;i++){//根據方法名擷取方法Method m=stu.getClass().getMethod(methodNames[i]);Class c=m.getReturnType();//擷取物件類型if(c.getName().equals("java.lang.Integer")||c.getName().equals()){int value=(Integer)m.invoke(s);stmt.setInt(i+1,value)}if(c.getName().equals("java.lang.String")){String value=(String)m.invoke(s);stmt.setString(i+1,value)}stmt.executeUpdate();stmt.close();conn.close();}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.