JAVA-Mybatis basics-framework setup and simple query, javamybatis

Source: Internet
Author: User

JAVA-Mybatis basics-framework setup and simple query, javamybatis

In JAVA, database operations include JDBC, hibernate, Mybatis, and other technologies. Today I have sorted out the following: Let's talk about Mybatis. Also sort out the documents for yourself;

Hibernate is a complete ORM framework and fully object-oriented. However, since all database operations are performed in the form of objects, SQL code is automatically generated by the framework, and the operability and flexibility are relatively lower than those of Mybatis. Therefore, Mybatis gradually becomes the standard configuration developed by most developers;

I. myBatis framework construction

The overall framework structure of myBatis is shown in. You can create the framework as is (the jar package is provided at the end of the article)

2. Compile the entity class corresponding to the database table

First, the database table structure is as follows (mysql database ):

1. Write the following code into object class User. java:
public class User {    @Override    public String toString() {        return "User [id=" + id + ", username=" + username + ", sex=" + sex                + ", address=" + address + ", birthday=" + birthday + "]";    }    private int id;    private String username;    private String sex;    private String address;    private Date birthday;    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 getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }    public String getAddress() {        return address;    }    public void setAddress(String address) {        this.address = address;    }    public Date getBirthday() {        return birthday;    }    public void setBirthday(Date birthday) {        this.birthday = birthday;    }}
2. Write the configuration file to SqlMapConfig. xml.
<! DOCTYPE configurationPUBLIC "-// mybatis.org//DTD Config 3.0 //" http://mybatis.org/dtd/mybatis-3-config.dtd "> <configuration> <! -- After integration with spring, environments configuration will be abolished --> <environments default = "development"> <environment id = "development"> <! -- Use jdbc Transaction Management --> <transactionManager type = "JDBC"/> <! -- Database connection pool --> <dataSource type = "POOLED"> <property name = "driver" value = "com. mysql. jdbc. driver "/> <property name =" url "value =" jdbc: mysql: // localhost: 3306/mybatis? CharacterEncoding = UTF-8 "/> <property name =" username "value =" root "/> <property name =" password "value =" 123456 "/> </dataSource> </ environment> </environments> <mappers> <mapper resource = "sqlmap/User. xml "> </mapper> </mappers> </configuration>

Note: The mysql account and password in SqlMapConfig must be changed to your own account and password.

3. Create log4j. properties (public file) under the config package)

Write the default parameters in the file:

# Global logging configuration. We recommend that you use debuglog4j in the development environment. rootLogger = DEBUG, stdout # Console output... log4j. appender. stdout = org. apache. log4j. leleappenderlog4j. appender. stdout. layout = org. apache. log4j. patternLayoutlog4j. appender. stdout. layout. conversionPattern = % 5 p [% t]-% m % n
4. Start writing User. xml
<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapperPUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <! -- Namespace: To isolate SQL statements and facilitate management, dao er develops dao and uses namespace for special purposes --> <mapper namespace = "test"> <! -- Configure many SQL statements in the mapper. xml file. When executing each SQL statement, the er. xml object is encapsulated as the MappedStatement object to manage SQL statements in statement units. --> <! -- Query user information by id --> <! -- Id: uniquely identifies a statement # {}: represents a placeholder. If a simple type parameter is input in # {}, the name in # {} is arbitrary. parameterType: Type of the input parameter, use # {} to receive the resultType parameter input by parameterType: output result type, whether multiple or single results are returned, specify the pojo type mapped to a single record --> <select id = "findUserById" parameterType = "int" resultType = "cn. qkp. mybatis. po. user "> SELECT * from user where id =#{ id} </select> </mapper>

After the preceding configuration is complete, the entire basic Mybatis framework is built. We can use the code to operate the database. Let's perform simple query operations on the database first;

========================================================== ===== Use Mybatis! ========================================================== ==============

1. Create a test class (MybatisFrist. java) in the first package)

The content code is:

Private SqlSessionFactory sqlsessionfactory; // stores the SqlSessionFactory object @ Before public void star () throws Exception {// sets the configuration path. mybitis uses SqlMapConfig. xml as the main path. Because mapper in SqlMapConfig is associated with user. xml // because it is in the config root directory, it can be referenced directly without the config String resource = "SqlMapConfig. xml "; // SqlMapConfig. use getResourceAsStream in the Resources class of mybitis to implement InputStream inputStream = Resources. getResourceAsStream (resource); // create SqlSessionFactory class sqlsessionfactory of Mybitis = new SqlSessionFactoryBuilder (). build (inputStream) ;}@ Test public void test () {// use the factory class to open the data interface SqlSession sqlsession SqlSession = sqlsessionfactory. openSession (); // set the receiving Object User user = null; try {// query the data selectOne. The first parameter of a method to query is user. namespace in xml. id; the second parameter is # {id} user = sqlsession in the user configuration file. selectOne ("test. findUserById ", 1);} catch (Exception e) {// TODO: handle exception} finally {sqlsession. close (); // close sqlsession} System after reading. out. println (user); // print the output}

Run the above Code and the result is:

The above information is successfully connected to the database and the specified data is obtained!

Ps: The preceding method is used to query a single value. to query a group of data, use the selectList method of SqlSession to receive a List. The Code is as follows:

In User. xml:

<select id="selectByName" parameterType="String" resultType="cn.qkp.po.User">select * from User where username like '%${value}%'</select>

PS: in xml, the # {} placeholder indicates that the system will automatically convert the java type and jdbc Type, while $ {} indicates the original output, using $ {} can cause SQL injection attacks. Use it with caution;

In the myBatisRun code:

@ Test public void star2 () {SqlSession sqlsession = sqlsessionfactory. openSession (); List <User> user = sqlsession. selectList ("test. selectByName "," James "); sqlsession. close (); System. out. println (user. get (0 ));}

Result:

 

Related jar package connection: http://pan.baidu.com/s/1dF9UtlJ

The above are basic frameworks and simple query operations. Other operations are being organized and released. Please wait ~~~~ Thank you !!!

 

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.