Simple use of mybatis and simple use of mybatis

Source: Internet
Author: User

Simple use of mybatis and simple use of mybatis

Package to be used: (here is only one version, other Baidu)

Mysql-connector-java-5.1.6-bin

Mybatis-3.2.2

First look at the project directory:


Configuration File mybatisconfig. xml:

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE configurationPUBLIC "-// mybatis.org//DTD Config 3.0 //" http://mybatis.org/dtd/mybatis-3-config.dtd "> <configuration> <! -- This item must be configured for XML ing! Specify the object class corresponding to the return value in mappers --> <! -- <TypeAliases> <typeAlias alias = "User" type = "com. miquan. mybatis. bean. User"/> </typeAliases> --> <! -- JDBC configuration --> <environments default = "development"> <environment id = "development"> <transactionManager type = "JDBC"/> <dataSource type = "POOLED"> <property name = "driver" value = "com. mysql. jdbc. driver "/> <property name =" url "value =" jdbc: mysql: // localhost: 3306/weixinface "/> <property name =" username "value =" root "/> <property name =" password "value =" "/> </dataSource> </environment> </environments> <! -- Mappers, each entity class corresponds to an xml --> <mappers> <mapper resource = "com/miquan/mybatis/bean/User. xml "/> </mappers> </configuration>

Entity class User. java:

package com.miquan.mybatis.bean;public class User {private int id;private String userName;private String password;public User(int id, String userName, String password) {super();this.id = id;this.userName = userName;this.password = password;}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 getPassword() {return password;}public void setPassword(String password) {this.password = password;}}

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 corresponds to the interface class --> <mapper namespace = "com. miquan. mybatis. inter. IUserOperation"> <! -- <Select id = "selectById" parameterType = "int" resultType = "User"> select * from User where id =#{ id} </select> --> </mapper>

IUserOperation. java:

package com.miquan.mybatis.inter;import java.util.List;import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update;import com.miquan.mybatis.bean.User;public interface IUserOperation {@Select("select * from User where id = #{id}")public User selectById(int id);@Select("select * from User where userName = #{userName}")public List<User> selectUsers(String userName);@Insert("insert into User values(null, #{userName}, #{password})")public boolean addUser(User user); @Delete("delete from User where id = #{id}")public boolean delUser(int id);@Update("update User "+ "set userName = #{userName}, "+ "password = #{password} "+ "where id = #{id}")public boolean updateUser(User user);}

Test. java:

Package com. miquan. mybatis. test; import java. io. inputStream; import java. util. list; 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 com. miquan. mybatis. bean. user; import com. miquan. mybatis. inter. IUserOperation; public class Test {static SqlSession session; public static void main (String [] args) {try {// obtain sessionInputStream is = Resources. getResourceAsStream ("mybatisconfig. xml "); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder (). build (is); session = sqlSessionFactory. openSession (); // XML configuration usage // User user User = session. selectOne ("com. miquan. mybatis. bean. userDB. selectById ", 1); // System. out. println (user. toString (); // interface call method // Note: After the insert, delete, and update methods are called, commit is required to change the data IUserOperation userOperation = session. getMapper (IUserOperation. class); // query // User user = userOperation. selectById (1); // System. out. println (user. toString (); // search for List // List <User> users = userOperation. selectUsers ("miquan"); // System. out. println (users. size (); // Add // User user = new User (); // user. setUserName ("zhiquan"); // user. setPassword ("999"); // userOperation. addUser (user); // session. commit (); // Delete // userOperation. delUser (7); // session. commit (); // Change User user = new User (8, "qiantu", "shaxppp"); userOperation. updateUser (user); session. commit ();} catch (Exception e) {e. printStackTrace ();} finally {try {session. close ();} catch (Exception e) {e. printStackTrace ();}}}}

Simple addition, deletion, query, and modification can be implemented.


What are the advantages and disadvantages of myBatis?

1. Advantages
Simple:
It is easy to learn and use. Through documents and source code, you can fully master its design ideas and implementation.
Practical:
It provides the data ing function, encapsulation of underlying data access (such as ado.net), and DAO framework, which makes it easier for us to develop and configure our DAL layer.
Flexibility:
Through SQL, we can basically implement all the functions that we can achieve without using the data access framework, maybe more.
Complete functions:
It provides connection management, cache support, thread support, (distributed) Transaction Management, and problems to be solved by configuring Data Access layers such as relational object ing. Provides DAO support and encapsulates ADO. NET, NHibernate, and DataMapper In the DAO framework.
Enhance system maintainability:
By providing the DAL layer, the business logic and data access logic are separated to make the system design clearer, easier to maintain, and easier to perform unit testing. Separation of SQL and Code improves maintainability.
2. Disadvantages
Lag:
There is no explicit support for. NET2.0. The latest version can be compiled in 2.0, but some unit tests cannot pass.
Immature, less engineering practice:
IbatisNet is rarely used in actual projects. It is theoretically feasible.
Semi-ORM, fewer tools supported:
We need to write SQL by ourselves, and.. NET has not found a tool that can automatically generate service layer classes and configuration files. This is different from nhib.pdf. nhib.pdf will generate SQL directly for our database, and there are some auxiliary tools. Therefore, using Ibatis requires more work than nhib.pdf.

Simple addition, deletion, modification, and query of spring mvc + mybatis are urgent,

The value is the same as that of jsp. request. setAttribute is used.

Related Article

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.