Java註解項目實戰即類比Hibenernate產生sql語句

來源:互聯網
上載者:User

標籤:java 註解 hibenernate sql

整理了近期學習java註解的部分代碼 ,藉助java註解類比Hibenernate ORM模型建立對象與sql語句的映射

Table 註解的建立

package com.imooc.test;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import javax.lang.model.element.Element;//用作類的註解,生命週期為運行時 一個值@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)public @interface Table {String value();}

欄位 註解的建立

package com.imooc.test;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/* * 範圍為欄位 運行時使用 * */@Target({ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)public @interface Column {String value();}

使用者表(類) 

package com.imooc.test;@Table("user")public class Filter { @Column("id") private int id;  @Column("user_name") private String userName;  @Column("user_name") private String nickName;  @Column("age") private int age;  @Column("city") private String city;  @Column("email") private String email;  @Column("mobile") private String mobile; public int getId() {  return id; } public void setId(int id) {  this.id = id; } public String getUserName() {  return userName; } public void setUserName(String userName) {  this.userName = userName; } public String getNickName() {  return nickName; } public void setNickName(String nickName) {  this.nickName = nickName; } public int getAge() {  return age; } public void setAge(int age) {  this.age = age; } public String getCity() {  return city; } public void setCity(String city) {  this.city = city; } public String getEmail() {  return email; } public void setEmail(String email) {  this.email = email; } public String getMobile() {  return mobile; } public void setMobile(String mobile) {  this.mobile = mobile; }}

測試類別的建立

package com.imooc.test;@Table("Coder ")public class Coder  {@Column("id")private int id;@Column("name")private String userName;@Column("age")private int age;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}

sql語句的產生過程

package com.imooc.test;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class Test { public static void main(String[] args) {  // 代碼如何與資料庫做映射  Filter f1 = new Filter();  f1.setId(10);  Filter f2 = new Filter();  f2.setUserName("lucy");  Filter f3 = new Filter();  f3.setEmail("[email protected],[email protected],[email protected]");  Coder c1 = new Coder();  c1.setUserName("ruanjianlin");  String sql1 = query(f1);  String sql2 = query(f2);  String sql3 = query(f3);  String sql4 = query(c1);  System.out.println(sql1);  System.out.println(sql2);  System.out.println(sql3);  System.out.println(sql4); } private static String query(Object f) {  // TODO Auto-generated method stub  StringBuilder sb = new StringBuilder();  // 1.擷取Class通過類的類類型得到類的詳細資料  Class c = f.getClass();  // Java Package.isAnnotationPresent()方法用法執行個體教程。方法返回true,如果指定類型的注釋存在於此元素上,  // 否則返回false  // 2.擷取Table的名字  boolean exists = c.isAnnotationPresent(Table.class);  if (!exists) {   return null;  }  Table t = (Table) c.getAnnotation(Table.class);  String tableName = t.value();  sb.append("select* from ").append(tableName).append(" where 1=1 ");  // 3遍曆所有欄位  Field[] fArray = c.getDeclaredFields();  for (Field field : fArray) {   // 4拿到每個欄位對應的sql   // 4.1欄位名   boolean fExists = field.isAnnotationPresent(Column.class);// 是否存在   // 判斷是否存在欄位   if (!fExists) {    continue;   }   Column column = field.getAnnotation(Column.class);   String columnName = column.value();   Object fieldValue = null;   String filedName = field.getName();   // 4.2拿到欄位值(先擷取欄位的get方法)   String getMethodName = "get"     + filedName.substring(0, 1).toUpperCase()     + filedName.substring(1);   try {    Method getMethod = c.getMethod(getMethodName);// 取得該值    // 反射渠道得到欄位值    fieldValue = getMethod.invoke(f);   } catch (SecurityException e) {    // TODO Auto-generated catch block    e.printStackTrace();   } catch (NoSuchMethodException e) {    // TODO Auto-generated catch block    e.printStackTrace();   } catch (IllegalArgumentException e) {    // TODO Auto-generated catch block    e.printStackTrace();   } catch (IllegalAccessException e) {    // TODO Auto-generated catch block    e.printStackTrace();   } catch (InvocationTargetException e) {    // TODO Auto-generated catch block    e.printStackTrace();   }   if (fieldValue == null     || (fieldValue instanceof Integer && (Integer) fieldValue == 0)) {    continue;   }   //4.3拼裝sql   sb.append("and ").append(columnName);   if (fieldValue instanceof String) {    if (((String) fieldValue).contains(",")) {     String[] values = ((String) fieldValue).split(",");     sb.append(" in(");     for (String v : values) {      sb.append("‘").append(v).append("‘,");     }     sb.deleteCharAt(sb.length() - 1);     sb.append(")");    } else {     sb.append("= ‘").append(fieldValue).append("‘");    }   } else {    sb.append("=").append(fieldValue.toString());   }  }  return sb.toString(); }}

650) this.width=650;" width="313" height="105" title="代碼.jpg" style="width:466px;height:60px;" alt="wKiom1iukDWTmOanAADwlnUlcDY319.jpg-wh_50" src="https://s1.51cto.com/wyfs02/M01/8D/E7/wKiom1iukDWTmOanAADwlnUlcDY319.jpg-wh_500x0-wm_3-wmp_4-s_1068315026.jpg" />

本文出自 “ruanjianlin” 部落格,請務必保留此出處http://ruanjianlin.blog.51cto.com/11146685/1900584

Java註解項目實戰即類比Hibenernate產生sql語句

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.