Classic cases of MyBatis and classic cases of MyBatis

Source: Internet
Author: User

Classic cases of MyBatis and classic cases of MyBatis

1. First, we first understand some jar packages of Mybatis.

--- And project framework

2. Next let's take a look at the configuration file (mybatis-config.xml) of mybatis)

 

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE configurationPUBLIC "-// mybatis.org//DTD Config 3.0 //" http://mybatis.org/dtd/mybatis-3-config.dtd "> <configuration> <! -- Alias --> <typeAliases> <package name = "cn. happy. entity "/> </typeAliases> <environments default =" development "> <environment id =" development "> <! -- Use jdbc transactions --> <transactionManager type = "JDBC"/> <! -- Use the built-in connection pool --> <dataSource type = "POOLED"> <property name = "driver" value = "oracle. jdbc. oracleDriver "/> <property name =" url "value =" jdbc: oracle: thin: @ localhost: 1521: orcl "/> <property name =" username "value =" happy "/> <property name =" password "value =" 1 "/> </dataSource> </environment> </environments> <mappers>
<! -- Connection configuration --> <mapper resource = "cn/happy/dao/StudentDAO. xml"/> </mappers> </configuration>

 

3. Small configuration on the dao layer (StudentDAO. xml)

 

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapperPUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <mapper namespace =" cn. happy. dao "> <! -- Add --> <insert id = "insertStudent"> insert into student (stuno, stuname, stuage, studate) values (ssm. nextval, # {stuname}, # {stuage}, # {studate}) <selectKey keyProperty = "stuno" resultType = "int"> select SSM. CURRVAL from dual </selectKey> </insert> <! -- Query all --> <select id = "findAll" resultType = "Student"> select * from student </select> <! -- Fuzzy query --> <select id = "findAllLike" resultType = "Student"> <! -- No matter why the parameter is available --> <! -- Select * from student where stuname like concat ('%', # {stuname}, '%') --> <! -- String --> <! -- Select * from student where stuname like '% $ {value} %' --> <! -- Object --> select * from student where stuname like '% $ {stuname} %' </select> <! -- Delete student --> <delete id = "delStudent"> delete from student where stuno =#{ id} <! -- # {Id} can be written as a placeholder --> </delete> </mapper>

 

 

4. entity layer entity class (Student)

 

package cn.happy.entity;import java.util.Date;public class Student {    private int stuno;    private String stuname;    private int stuage;    private Date studate;    public String toString() {        return "Student [stuno=" + stuno + ", stuname=" + stuname + ", stuage="                + stuage + ", studate=" + studate + "]";    }    public int getStuno() {        return stuno;    }    public void setStuno(int stuno) {        this.stuno = stuno;    }    public String getStuname() {        return stuname;    }    public void setStuname(String stuname) {        this.stuname = stuname;    }    public int getStuage() {        return stuage;    }    public void setStuage(int stuage) {        this.stuage = stuage;    }    public Date getStudate() {        return studate;    }    public void setStudate(Date studate) {        this.studate = studate;    }    }

 

 

5. dao layer (IStudentDAO)

 

Package cn. happy. dao; import java. io. IOException; import java. util. list; import cn. happy. entity. student; public interface IStudentDAO {/** add Student information */public int addStu (Student stu) throws IOException;/** query all */public List <Student> findAll () throws IOException;/** fuzzy query */public List <Student> findAlllike (Student stu) throws IOException; /** fuzzy query String */public List <Student> findAlllikebstuname (String stuname) throws IOException;/** Delete */public int delStudent (int id) throws IOException ;}

 

 

6. impl layer (IStudentDAOImpl) under dao Layer)

 

Package cn. happy. dao. impl; import java. io. IOException; import java. util. list; import org. apache. ibatis. session. sqlSession; import cn. happy. dao. IStudentDAO; import cn. happy. entity. student; import cn. happy. util. mybatisUtil; public class IStudentDAOImpl implements IStudentDAO {/** session member variable */SqlSession session;/** add * (non-Javadoc) * @ see cn. happy. dao. IStudentDAO # addStu (cn. happy. entity. student) */public int addStu (Student stu) throws IOException {// get session = MybatisUtil. getSession (); // Add insert int result = session. insert ("insertStudent", stu); // Add transaction session. commit (); // close the session. close (); return result;}/** query all * (non-Javadoc) * @ see cn. happy. dao. IStudentDAO # fandAll () */public List <Student> findAll () throws IOException {// get session = MybatisUtil. getSession (); List <Student> list = session. selectList ("findAll"); // closes the session. close (); return list;}/** fuzzy query * 1. the parameter is the object * (non-Javadoc) * @ see cn. happy. dao. IStudentDAO # findAll (cn. happy. entity. student) */public List <Student> findAlllike (Student stu) throws IOException {// get session = MybatisUtil. getSession (); List <Student> list = session. selectList ("findAllLike", stu); // close the session. close (); return list;}/** fuzzy query * 2. the parameter is a string * (non-Javadoc) * @ see cn. happy. dao. IStudentDAO # findAll (cn. happy. entity. student) */public List <Student> findAlllikebstuname (String stuname) throws IOException {// get session = MybatisUtil. getSession (); System. out. println ("222"); List <Student> list = session. selectList ("findAllLike", stuname); System. out. println ("333"); // closes the session. close (); return list;}/** Delete */public int delStudent (int id) throws IOException {// get session = MybatisUtil. getSession (); int result = session. delete ("delStudent", id); session. commit (); return result ;}}

 

 

7. util tool class (MybatisUtil)

 

Package cn. happy. util; import java. io. IOException; import java. io. reader; import org. apache. ibatis. io. resources; import org. apache. ibatis. session. sqlSession; import org. apache. ibatis. session. sqlSessionFactory; import org. apache. ibatis. session. sqlSessionFactoryBuilder;/*** tool class * @ author Happy **/public class MybatisUtil {private static String config = "mybatis-config.xml"; static Reader reader; static {try {reader = Resources. getResourceAsReader (config);} catch (IOException e) {e. printStackTrace () ;}} private static SqlSessionFactory factory = new SqlSessionFactoryBuilder (). build (reader); // provides a method for obtaining the session public static SqlSession getSession () throws IOException {// 1.1 what is done by openSession SqlSession session = factory. openSession (); System. out. println ("3333"); return session ;}}

 

 

8. log information configuration file (log4j. properties)

 

### Direct log messages to stdout ### log4j. appender. stdout = org. apache. log4j. leleappenderlog4j. appender. stdout. target = System. outlog4j. appender. stdout. layout = org. apache. log4j. patternLayoutlog4j. appender. stdout. layout. conversionPattern = % d {ABSOLUTE} % 5 p % c {1}: % L-% m % n ### direct messages to file mylog. log ### log4j. appender. file = org. apache. log4j. fileAppenderlog4j. appender. file. file = c \: mylog. loglog4j. appender. file. layout = org. apache. log4j. patternLayoutlog4j. appender. file. layout. conversionPattern = % d {ABSOLUTE} % 5 p % c {1 }: % L-% m % n ### set log levels-for more verbose logging change 'info' to 'debug '###
// Record the information in the cn. happy. dao package log4j.logger.cn. happy. dao = trace, stdout

 

 

So much for now. If you want to know more, remember to pay more attention !!!!

 

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.