Getting started with MyBaits: one-to-one query of one-on-one tables

Source: Internet
Author: User

Getting started with MyBaits: one-to-one query of one-on-one tables

1. Basic concepts of MyBaits: omitted

2. Case: Requirement: Create a database query, one-to-one

3. Development steps:

  • (1). Create a database + Table
  • (2). Add package
  • (3) define object classes
  • (4). Write db. properties to write database information into it; write the conf. xml file of MyBatis configuration file, introduce db. properties; Introduce alias
  • (5) define the SQL ing file *** Mapper. xml file
  • (6). register the *** er. xml file to the conf. xml file.
  • (7) Compile the MyBaitsUtils Tool
  • (8). Test

4. Code

(1). Add package

  

(2). create databases and tables

CREATE TABLE teacher(    t_id INT PRIMARY KEY AUTO_INCREMENT,     t_name VARCHAR(20));CREATE TABLE class(    c_id INT PRIMARY KEY AUTO_INCREMENT,     c_name VARCHAR(20),     teacher_id INT);ALTER TABLE class ADD CONSTRAINT fk_teacher_id FOREIGN KEY (teacher_id) REFERENCES teacher(t_id);    INSERT INTO teacher(t_name) VALUES('LS1');INSERT INTO teacher(t_name) VALUES('LS2');INSERT INTO class(c_name, teacher_id) VALUES('bj_a', 1);INSERT INTO class(c_name, teacher_id) VALUES('bj_b', 2);

(3) define object classes

package com.atguigu.mybatis.domain;/** * @author hp * */public class Classes {    private int id;    private String name;        private Teacher teacher;    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 Teacher getTeacher() {        return teacher;    }    public void setTeacher(Teacher teacher) {        this.teacher = teacher;    }    public Classes(int id, String name, Teacher teacher) {        super();        this.id = id;        this.name = name;        this.teacher = teacher;    }    public Classes() {            }    @Override    public String toString() {        return "Classes [id=" + id + ", name=" + name + ", teacher=" + teacher + "]";    }        }
View Code
package com.atguigu.mybatis.domain;/** * @author hp * */public class Teacher {    private int id;    private String name;    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 Teacher(int id, String name) {        super();        this.id = id;        this.name = name;    }        public Teacher() {        }    @Override    public String toString() {        return "Teacher [id=" + id + ", name=" + name + "]";    }            }
View Code

(4). Write db. properties to write database information into it;

username=rootpassword=lfdyjdbcUrl=jdbc:mysql://localhost:3306/mybatis1driverClass=com.mysql.jdbc.Driver

Compile the configuration file conf. xml of MyBatis and introduce db. properties;

1 <! -- Load db. properties --> 2 <properties resource = "db. properties"> </properties>
3 <! -- Configure database connection information --> 4 <environments default = "development"> 5 <environment id = "development"> 6 <transactionManager type = "JDBC"/> 7 <dataSource type = "POOLED"> 8 <property name = "driver" value = "$ {driverClass}"/> 9 <property name = "url" value = "$ {url}"/> 10 <property name = "username" value = "$ {username}"/> 11 <property name = "password" value = "$ {password}"/> 12 </dataSource> 13 </environment> 14 </environments>

Introduce alias

<! -- Add an alias --> <typeAliases> <package name = "com. atguigu. mybatis. domain"/> </typeAliases>

(5) define the SQL ing file *** Mapper. xml file

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapper PUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <! -- Compile the corresponding CRUD --> <mapper namespace = "com. atguigu. mybatis. mapper. ClassMapper"> <! -- Method 1: Nested results, use nested results to process the subset of repeated Union results --> <select id = "getClass" parameterType = "int" resultMap = "ClassResultMap"> select * from class c, teacher t where c. teacher_id = t. t_id and c. c_id = # {id} </select> <resultMap type = "Classes" id = "ClassResultMap"> <id property = "id" column = "c_id"/> <result property = "name" column = "c_name"/> <association property = "teacher" javaType = "Teacher"> <id property = "id" column = "t_id"/> <result property = "name" column = "t_name"/> </association> </resultMap>

  

  

<! -- Method 2: Nested query, using another SQL statement to return the expected complex type -->
<Select id = "getClass2" parameterType = "int" resultMap = "ClassResultMap2">
Select * from class where c_id = # {id}
</Select>

<Select id = "getteacher" parameterType = "int" resultType = "Teacher">
Select t_id id, t_name name from teacher where t_id = # {id}
</Select>

<ResultMap type = "Classes" id = "ClassResultMap2">
<Id property = "id" column = "c_id"/>
<Result property = "name" column = "c_name"/>
<Association property = "teacher" column = "teacher_id" select = "getteacher">
</Association>
</ResultMap>

</mapper>

(6). register the *** er. xml file to the conf. xml file.

<! -- Register the mapper file for SQL ing --> <mappers> <mapper resource = "com/atguigu/mybatis/mapper/ClassMapper. xml"/> </mappers>

(7) Compile the MyBaitsUtils Tool

package com.atguigu.mybatis.test;import java.io.InputStream;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class MyBatisUtils {        public static SqlSessionFactory getFactory(){        String resource = "conf.xml";                InputStream is = MyBatisUtils.class.getClassLoader().getResourceAsStream(resource);                SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);                    return factory;    }}

(8). Test

package com.atguigu.mybatis.test;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import com.atguigu.mybatis.domain.Classes;/** * @author hp * */public class MyBatisTest {        public static void main(String[] args) {                SqlSessionFactory sessionFactory = MyBatisUtils.getFactory();                SqlSession session = sessionFactory.openSession();                String statement = "com.atguigu.mybatis.mapper.ClassMapper.getClass";                Classes c = session.selectOne(statement, 1);        System.out.println(c);                session.close();                }}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

      

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.