Hibernate O/R Mapping類比

來源:互聯網
上載者:User

標籤:

作為SSH中的重要一環,有必要理解一下Hibernate對 O/R Mapping的實現。

主要利用java的反射機制來得到完整的SQL語句。

準備工作:

1. Object

Student實體類:

public class Student {    private int id;    private String name;    private int age;    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 int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }}

2. Relationship

_student表:

-- database: hibernatecreate table _student(_id int primary key auto_increment,_age int,_name varchar(20));

3. 類比O/R Mapping:

針對Student實體類的SessionStu (完成Student對象的持久化):

public class SessionStu {    private String tableName;    private Map<String, String> field2Column = new HashMap<String,String>();    private String[] fields;        public SessionStu() {        // 以下內容應當通過解析xml的方式build出來        // 該樣本僅僅示範Hibernate的核心部分:O/R Mapping (利用反射得到完整sql)        tableName = "_student";        field2Column.put("id","_id");        field2Column.put("name","_name");        field2Column.put("age","_age");        fields = new String[field2Column.size()];        try {            Class.forName("com.mysql.jdbc.Driver");        } catch (ClassNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }        public void save(Student student) throws Exception {        // TODO Auto-generated method stub        String sql = createSQL();        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hibernate","root","");        PreparedStatement ps = conn.prepareStatement(sql);        ps = setParameters(ps,student);        ps.executeUpdate();        ps.close();        conn.close();    }        //important    private PreparedStatement setParameters(PreparedStatement ps, Student student) throws Exception{        for (int i = 0; i < fields.length; i++) {            String get_method = "get"+(char)(fields[i].charAt(0)-32)+fields[i].substring(1);            Method m = student.getClass().getMethod(get_method);            String type = m.getReturnType().getName();            String te = type.substring(type.lastIndexOf(".")+1);            switch (te) {            case "int":                ps.setInt(i+1, (int) m.invoke(student));                break;            case "String":                ps.setString(i+1, (String) m.invoke(student));            default:                break;            }        }        return ps;            }        private String createSQL(){        String columnsStr = "";        int index = 0;        for (String key : field2Column.keySet()) {            fields[index] = key;            columnsStr += (field2Column.get(key) + ",");            index++;        }        columnsStr = columnsStr.substring(0, columnsStr.length()-1);        String unknow = "";        for (int i = 0; i < field2Column.size(); i++) {            unknow += "?,";        }        unknow = unknow.substring(0,unknow.length()-1);        String sql = "insert into " + this.tableName + " (" + columnsStr +") values (" + unknow +")";        System.out.println(sql);        return sql;    }    }

4. Test:

public class TestSessionSave {    public static void main(String[] args) throws Exception {        Student student = new Student();        student.setAge(20);        student.setId(5);        student.setName("hibernate");        SessionStu ss = new SessionStu();        ss.save(student);    }}

5. Done

Hibernate O/R Mapping類比

聯繫我們

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