Mybatis of Java development framework

mybasits profile writing
1.configer configuration file
<xml Version = "1.0" encoding = "UTF-8"??>
<DOCTYPE the Configuration!
the PUBLIC "- // mybatis.org//DTD Config 3.0 // EN"
" HTTP: //mybatis.org/dtd/mybatis-3-config.dtd "> ;
<Configuration>
! <- using the log control Mybaits ->
<Settings>
<Setting name =" logImpl "value =" LOG4J "/>
</ Settings>
<Environments default = "default"> <-! define all database links, and specify which data source ->
<Environment the above mentioned id = "default"> <-! defined data source name - >
<the transactionManager type = "the JDBC" /> <-! submission of transaction types ->
<type the dataSource = "the POOLED"> <-! define a data source,Connection database connection pooling mode ->
<Property name = "Driver" value = "com.mysql.cj.jdbc.Driver" />
<Property name = "url" value = "jdbc: MySQL: //127.0.0.1:? 3306 / test4012 characterEncoding = utf8 & serverTimezone = GMT" />
<Property name = "username" value = "root" />
<Property name = "password" value = "root" />
</ dataSource>
</ Environment>
</ Environments>
<-! loaded database links when loading sql maps ->
<mappers>
<Resource Mapper = "COM / POJO /usermapper-4012.xml "/>
<by mappers>
</ configuration>
2.mapper configuration file
(1) resultType return value type
(2) pramatetertype parameters are passed
<? xml version =" 1.0 " encoding =" UTF -8 ">?
<DOCTYPE Mapper!
the PUBLIC" - // mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">;
<mapper namespace = "com.service.IUserDao4012"> <-! interface address ->
<! - represents a declaration package name for the database operation ->
<! - The method of operating a database statement ->
<! - the entire contents of the query process ->
<SELECT ID = "the SelectAll" the resultType = "com.pojo.User4012">
the SELECT * the FROM table4012
limit offset # {}, {#} pageSize
</ SELECT>
<! - - insertion ->
<iNSERT ID = "InsertUser" the parameterType = "com.pojo.User4012">
iNSERT INTO table4012 (ID, username, Number, mybasits, Android, JavaEE) values (ID # {}, {#} username , Number # {}, {#} mybasits, Android # {}, {#} JavaEE)
</ INSERT>
<Delete ID = "DeleteUser" the parameterType = "com.pojo.User4012">
Delete from table4012 ID = # {WHERE ** }
</delete>
<update id="UpdateUser" parameterType="com.pojo.User4012">
update table4012 set username=#{username},number =#{number},mybasits=#{mybasits},android=#{android},javaee=#{javaee} where id=#{id}
</update>
<select id="findcount" parameterType="com.pojo.PageWays">
SELECT count (
) from table4012
</select>
<select id="findpage" parameterType="com.pojo.PageWays">
SELECT * from table4012
</select>
</mapper>
3.util类配置
package com.SelfStudy.util;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
public class Util {
private static SqlSessionFactory build;//定义一个对象
static {
String s="mybatis.config.xml";//加载config文件
InputStream inputStream=null;//输入输出流
try {
inputStream= Resources.getResourceAsStream(s);
build=new SqlSessionFactoryBuilder().build(inputStream);
}
catch (Exception e){
e.printStackTrace();
}
finally {
try {
if ( inputStream !=null){
inputStream.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
public static SqlSession getSession(){
return build.openSession();
}
}
4.log4j.properties文件配置
log4j.appender.console =org.apache.log4j.ConsoleAppender
log4j.appender.console.Target =System.out
log4j.appender.console.layout =org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern =[%-5p][%d{yyyy-MM-dd HH:mm:ss}] %c %L %m%n

\u914D\u7F6E\u6839

Debug = Log4j.rootLogger, Console
## log4j.logger.com.mapper.StudentMapper = Debug, Console
four dynamic sql
using tag 1.if set
the Select from Table
IF (Test = "name! = null and name! = ' ' ") {
# {ID}
}
If each of the database to add a statement later added,
IF (Test =" name! = null and name! =' ' ") {
#} {ID,
}
using the tag 2.where
SELECT
from Table
<WHERE>
IF (Test = "name! = null and name! = ''") {
name = # {name}
}
if add a database statement for each one behind added,
IF (Test = "ID! = ID and null! = '' ") {
ID = # {ID}
}
</ WHERE>
using 3.choose when tag
<WHERE>
<the Choose>
<when test="name!=null and name!=''">
and name=#{name}
</when>
<when></when>
</choose>
</where>

  1. set标签的使用
    uddate Table
    set id=#{id}
    <where>
    <if></if>
    </where>
  2. Use trim tag
    <Update ID = "UPD" the parameterType = "Teacher">
    Update Teacher
    <trim prefix = "SET" suffixOverrides = ",">
    name = # {name}, Age = # {Age},
    </ trim>
    WHERE ID = # {ID}
    </ Update>
    prefix = "be added in front of"
    prefixOverrides = "be removed earlier"
    suffix = "add back"
    suffixOverrides = "be removed later in"
    key: sequential execution prior removal then add
  3. bind标签
    <bind nam="nam" valus="'%'+nam+'%'"></bind>
    slct * from tabl wr nam lik #{nam}
  4. foreach (collection query, add)
    <the foreach collecation = "" Open = "" Close = "" Item = "">
    INSERT INTO Table () valuse
    <IF Test = "">
    # {},
    </ IF>
    </ the foreach >
    Collection: incoming parameter type
    open: open
    close: Close ways
    item: item
  5. selectKey using (a property of a record on the query)
    <INSERT>
    INSERT Table valuse ()
    <selectKey keyProperty = "" resultType = "" Order = "" keycolum = ""> </ selectKey>
    SELECT last_insert_name ()
    </ INSERT >
    keypropert is the name of the attribute query
    resulttype XM is www.fx61.com/brokerlist/xm.html agent for the return type, the query result is the return type of
    order execution order
    keycolum: attribute database corresponding
    plurality of query methods using
    1. fuzzy query
    SELECT from Table WHERE name = # {name}
    [. 1] when the correct query
    the SelectAll ( "Ko%%");
    [2] in the sql statement corrected
    using concat function
    SELECT
    from Table WHERE
    ID = concat ( '%', # { id}, '%')
  6. Combined multi-table queries
    (1) Configuration mapper class file
    <! - First, the encapsulated contents of the query ->
    <The resultMap ID = "SelectTogether01" type = "com.SelfStudy.pojo.PeopleWithDatil"> // package connection class properties, mainly the main class attribute
    <ID property = "detailID" column = "ID"> </ ID>
    <Result property = "address" column = "address"> </ Result>
    <Result property = "Country" column = "Country"> </ Result>
    <Property Result = "City" = column "City"> </ Result>
    <Property association = "PeopleDatil" the javaType = "com.SelfStudy.pojo.People"> // association with the package All properties subclass
    <property ID = "detailID" column = "ID"> </ ID>
    <property Result = "name" column = "name"></result>
    <result property="phone" column="phone"></result>
    </association>
    </resultMap>
    <select id="SelectTogether" resultMap="SelectTogether01">
    SELECT * FROM people, peopledatil // joint inquiry, dynamic SQL
    <WHERE>
    people. id= Peopledatil. id
    </ WHERE>
    </ SELECT>
    (2) Test Test class br /> @ org.junit.Test
    public void TestTogether () {
    the session = Util.getSession the SqlSession ();
    peopleMapperDao peopleMapperDao = session.getMapper (PeopleMapperDao.class);
    peopleMapperDao.SelectTogether ();
    List <People> List = null;
    List peopleMapperDao.SelectTogether = ();
    System.out.println (List );
    }
    3. one joint inquiry
    configuration class files
    Package Penalty for com.pojo;
    public class Student {
    Private String name;
    Private Integer id;
    Private Integer tid; // id and teachers in the dependent
    private String address;
    City String Private;
    // a teacher student corresponding to a
    private Teacher teacher; // query the teacher student
    public String getName () {
    return name;
    }
    public void the setName (String name) {
    this.name = name;
    }
    public Integer getId () {
    return ID;
    }
    public void the setId (Integer ID) {
    this.id ID =;
    }
    public gettid Integer () {
    return TID;
    }
    public void setTid (Integer TID) {
    this.tid TID =;
    }
    public String getAddress () {
    return address;
    }
    public void the setAddress (String address) {
    this.address = address;
    }
    public String getCity () {
    return City;
    }
    public void setCity(String city) {
    this.city = city;
    }
    public Teacher getTeacher() {
    return teacher;
    }
    public void setTeacher(Teacher teacher) {
    this.teacher = teacher;
    }
    public Student(String name, Integer id, Integer tid, String address, String city, Teacher teacher) {
    this.name = name;
    this.id = id;
    this.tid = tid;
    this.address = address;
    this.city = city;
    this.teacher = teacher;
    }
    public Student() { }
    br/>@Override
    public String toString() {
    return "Student{" +
    "name='" + name + '\'' +
    ", id=" + id +
    ", tid=" + tid +
    ", address='" + address + '\'' +
    ", city='" + city + '\'' +
    ", teacher=" + teacher +
    '}';
    }
    }
    接口配置
    package com.service;
    import com.pojo.Student;
    import java.util.List;
    public interface StudentDao {
    public List<Student> Selectall();
    public List<Student> SelectByid(Integer id);
    //查询所有学生
    public List<Student> SelectAllStudent();
    public List<Student> selct01();
    }
    mapper文件配置
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "
    http://mybatis.org/dtd/mybatis-3-mapper.dtd">;
    <mapper namespace="com.service.StudentDao">
    <resultMap id="map" type="com.pojo.Student">
    <id column="id" property="id"></id>
    <result property="name" column="name"></result>
    <result property="address" column="address"></result>
    <result property="city" column="city"></result>
    <result property="tid" column="tid"></result>
    <association property="teacher" column="tid" select="com.service.TeacherDao.SelectByid"></association>
    </resultMap>
    <!--联合查询-->
    <select id="selct01" resultType="com.pojo.Student">
    SELECT s.name, s.id ,s.tid ,s.address , s.city ,t.name , school ,age , sex,t.id
    FROM student s LEFT JOIN teacher t on
    s.tid=t.id
    </select>
    4.多对一联合查询
    <resultMap id="map01" type="com.pojo.Teacher">
    <id property="id1" column="id1" ></id>
    <result column="name1" property="name1"></result>
    <result column="school" property="school"></result>
    <result column="age" property="age"></result>
    <result column="sex" property="sex"></result>
    <collection property="students" ofType="com.pojo.Student">
    <id column="id" property="id"></id>
    <result column="name" property="name"></result>
    <result column="tid" property="tid"></result>
    <result column="address" property="address"></result>
    <result column="city" property="city"></result>
    </collection>
    </resultMap>
  7. 多对多的联合查询
    实体类的配置
    package com.pojo;
    import java.util.Date;
    import java.util.List;
    public class Writer {
    private String name;
    private Integer id;
    private Integer age;
    private String sex;
    private String book;
    private Date birthday;
    //查询作者里面包含作品
    private List<Works> works;
    public List<Works> getWorks() {
    return works;
    }
    public void setWorks(List<Works> works) {
    this.works = works;
    }
    public Writer(List<Works> works) {
    this.works = works;br/>}
    @Override
    public String toString() {
    return "Writer{" +
    "name='" + name + '\'' +
    ", id=" + id +
    ", age=" + age +
    ", sex='" + sex + '\'' +
    ", book='" + book + '\'' +
    ", birthday=" + birthday +
    ", works=" + works +
    '}';
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public Integer getId() {
    return id;
    }
    public void setId(Integer id) {
    this.id = id;
    }
    public Integer getAge() {
    return age;
    }
    public void setAge(Integer age) {
    this.age = age;
    }
    public String getSex() {
    return sex;
    }
    public void setSex(String sex) {
    this.sex = sex;
    }
    public String getBook() {
    return book;
    }
    public void setBook(String book) {
    this.book = book;
    }
    public Date getBirthday() {
    return birthday;
    }
    public void setBirthday(Date birthday) {
    this.birthday = birthday;
    }
    public Writer(String name, Integer id, Integer age, String sex, String book, Date birthday) {
    this.name = name;
    this.id = id;
    this.age = age;
    this.sex = sex;
    this.book = book;
    this.birthday = birthday;
    }
    public Writer() { }
    }
    mapper文件配置
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "
    http://mybatis.org/dtd/mybatis-3-mapper.dtd">;
    <mapper namespace="com.service.WriterDao">
    <!--所有作者-->
    <select id="SelectAllWriter" resultType="com.pojo.Writer">
    select from writer w
    </select>
    <select id="SelectWriterByid" resultType="com.pojo.Writer">
    select
    from writer w
    <where>
    id=#{id}
    </where>
    </select>
    <resultMap id="map01" type="com.pojo.Writer">
    <id property="id" column="id"></id>
    <result column="name" property="name"></result>
    <result column="age" property="age"></result>
    <result column="sex" property="sex"></result>
    <result column="book" property="book"></result>
    <result column="birthday" property="birthday"></result>
    <collection property="works" ofType="com.pojo.Works">
    <id property="book_id" column="book_id"></id>
    <id property="book_name" column="book_name"></id>
    <id property="book_press" column="book_press"></id>
    <id property="press_date" column="press_date"></id>
    </collection>
    </resultMap>
    <select id="SelectAllWriterAndWorks" resultMap="map01">
    SELECT w.age,w.birthday,w.book,w.id,w.name,w.sex ,o.book_id,o.book_press,o.press_date,o.book_name
    FROM writer w LEFT JOIN information i ON w.id=i.writer_idLEFT JOIN works o ON o.book_id=i.works_idbr/></select>
    </mapper>
    注解方式配置
    @Results(value={
    @Result(id=true,column="",property=""),
    br/>@Result(column="",property=""),
    @Result(column="",property=""),
    br/>@Result(column="",property=""),
    @Result(column="",property=""),
    br/>@Result(column="",property=""),
    @Result(column="",property=""), @Result(column="tid",property="works",many=@Many(Select="com.service.iuserdao.workByid") ),
    br/>})
    @Select(".......")
    java导入Excel表格
  8. Import package
    <dependency>
    <the groupId> org.apache.poi </ the groupId>
    <the artifactId> POI </ the artifactId>
    <Version> 3.17 </ Version>
    </ dependency>
    <-!
    Https://mvnrepository.com/artifact / Commons-IO / IO-Commons ->
    <dependency>
    <the groupId> Commons-IO </ the groupId>
    <the artifactId> Commons-IO </ the artifactId>
    <Version> 2.4 </ Version>
    </ dependency>
    // import dependencies
    2. the method of constructing
    public class ImportExcel {
    methods excel file // import
    public void ReadExcel (file file) {
    List List = new new the ArrayList <String> <> ();
    // incoming path. 1 Excel file to be imported.
    the try {
    // 2.Read file contents
    HSSFWorkbook workbook = new HSSFWorkbook (FileUtils.openInputStream ( file));
    // read sheet 3 page document, Excel sheet is in each table, the sheet is workboo page.
    HSSFSheet sheet = workbook.getSheetAt (0);
    // 4 to start reading the table of contents.
    Int the StartLine = 0; // start line number of rows, i.e. from 0 to the last row
    int endline = sheet.getLastRowNum () + 1 ; // the last row in the table d
    // through each row
    Map <Integer, Map <Integer, Map the HashMap >> = new new Object <> ();
    // a first row, first column, the value
    // iterate row
    for (int. 1 = A; A <endline; A ++) {
    HSSFRow HSSFRow = sheet.getRow (A) ;
    // traversing column
    // write a set value and rank
    the Map <Integer, Object> new new Result = the HashMap <> ();
    int endcell hssfRow.getLastCellNum = ();
    for (int J = 0; J <endcell; J ++ ) {
    result.put (J, hssfRow.getCell (J)); // number of rows with columns to acquire
    }
    map.put (A, Result);
    }
    List <People> = new new List1 the ArrayList <> ();
    for (Integer xxx:map.keySet()){
    System.out.print(map.get(xxx).get(0));
    System.out.print(map.get(xxx).get(1));
    System.out.print(map.get(xxx).get(2));
    System.out.print(map.get(xxx).get(3));
    People people=new People();
    people.setName(String.valueOf(map.get(xxx).get(0)));
    String java=String.valueOf(map.get(xxx).get(1));
    Integer java1=Integer.parseInt(java.substring(0, java.indexOf(".")));
    people.setJava(java1);
    String mybas=String.valueOf(map.get(xxx).get(2));
    Integer mybas1=Integer.parseInt(mybas.substring(0, mybas.indexOf(".")));
    people.setMybas(mybas1);
    String androi=String.valueOf(map.get(xxx).get(3));
    Integer androi1=Integer.parseInt(androi.substring(0, androi.indexOf(".")));
    people.setAndroi(androi1);
    list1.add(people);
    }
    SqlSession session= Util.getSession();
    PeopleMapperDao peopleMapperDao=session.getMapper(PeopleMapperDao.class);
    peopleMapperDao.ExcelInsert(list1);
    session.commit();
    }
    catch (Exception e){
    e.printStackTrace();
    }
    }
    }
  9. The method calls br /> @ org.junit.Test
    public void TestExcel () {
    ImportExcel new new ImportExcel AAA = ();
    File File = new new File ( "C: / the Users / Lenovo / Desktop / Study / SSM notes /test4012.xls" );
    aaa.ReadExcel (File);
    }

Guess you like

Origin blog.51cto.com/14511863/2448204