In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
From the beginning of the work to the present, the ORM framework used is Hibernate. I have heard of ibatis, but I have always seen the specific usage.
During the interview some time ago, I found that several companies asked if they could ibatis, so I studied it in the last few days, and then summarized it in my blog.
This summary is an introduction to ibatis, explaining some basic applications of ibatis and what we can do with ibatis in peacetime.
The word iBATIS, which comes from a combination of "internet" and "abatis", is an open source project launched by Clinton Begin in 2002. It was hosted by Google on June 16, 2010 and renamed MyBatis. Is a persistence layer framework that supports Java and NET based on SQL mapping.
The above content comes from Baidu encyclopedia. Because ibatis has changed its name to mybatis, I will be called mybatis later.
Like hibernate, mybatis is an ORM framework that encapsulates our database operations and improves development efficiency.
Through learning, I learned that mybatis is only a semi-automated ORM implementation, and we need to write sql ourselves, instead of directly defining the mapping between entities and data tables as hibernate does.
Let's use an example to get the first experience of mybatis.
1. Get mybatis
Like other open source frameworks, we need to download the corresponding jar package before we can use it
two。 Preparatory work
1) Open my eclipse and create a java web project. I call it mybatis here.
2) decompress the downloaded mybatis-3.2.7.zip, find the mybatis-3.2.7.jar in it, and add it to build path
3) add the jar packages that you may need to build path under the lib directory: asm-3.3.1.jar and cglib-2.2.2.jar. If you need other jar packages in the process, add them separately.
4) because mybatis is an ORM framework, we can't do without databases. I use Oracle 10g here and add oracle drivers to build path.
3. Prepare data
Or because I want to use mybatis, I have prepared several tables and inserted data into them.
Create table t_user (id number (10) primary key,name varchar2, org_id number (10)); insert into t_user (id,name,org_id) values (1); insert into t_user (id,name,org_id) values (2); insert into t_user (id,name,org_id) values (3) Wang Wu Insert into t_user (id,name,org_id) values; insert into t_user (id,name,org_id) values; create table t_role (id number (10) primary key,name varchar2; insert into t_role (id,name) values; insert into t_role (id,name) values Insert into t_role (id,name) values (3); insert into t_role (id,name) values (4)); create table t_user_role (user_id number (10), role_id number (10)); insert into t_user_role (user_id,role_id) values (1); insert into t_user_role (user_id,role_id) values (2); insert into t_user_role (user_id,role_id) values (3) Insert into t_user_role (user_id,role_id) values (4); insert into t_user_role (user_id,role_id) values (5); create table t_org (id number (10) primary key,name varchar2); insert into t_org (id,name) values (1); insert into t_org (id,name) values (2)); insert into t_org (id,name) values (3)
The simplest example of 4.mybatis
Let's complete the simplest example of mybatis
Hibernate has a core configuration called hibernate.cfg.xml, while the core configuration name of mybatis is mybatis-config.xml.
To complete a basic mybatis-config.xml configuration:
Transaction management and connection pool settings are configured under the environments element.
Under the mappers element, configure our mapping file path.
From the core configuration, we can see that we need to configure a mapping file. Before configuring the mapping file, we create the corresponding pojo model according to the table we built.
User.java
Package com.yu.model;public class User {private Long id; private String name; private Org org; public Long getId () {return id;} public void setId (Long id) {this.id = id;} public String getName () {return name } public void setName (String name) {this.name = name;} public Org getOrg () {return org;} public void setOrg (Org org) {this.org = org;}}
Org.java
Package com.yu.model;import java.util.ArrayList;import java.util.List;public class Org {private Long id; private String name; private List users = new ArrayList (); public Long getId () {return id;} public void setId (Long id) {this.id = id } public String getName () {return name;} public void setName (String name) {this.name = name;} public List getUsers () {return users;} public void setUsers (List users) {this.users = users;}}
Role.java
Package com.yu.model;public class Role {private Long id; private String name; public Long getId () {return id;} public void setId (Long id) {this.id = id;} public String getName () {return name } public void setName (String name) {this.name = name;}}
Configure UserMapper.xml
Select * from t_user select * from t_user where id = # {id} select * from t_user where name like'%'| # {name} | |'% 'insert into t_user (id,name) values (# {id}) # {name}) update t_user set name = # {name} where id = ${id} delete t_user where id = # {id}
As can be seen from the configuration, we have configured common operations such as add, delete, change, check, condition check, fuzzy search and so on.
5. Get mybatis up and running
After configuring the main configuration, let's take a look at how to use our java program to operate on mybatis.
First, review the process of manipulating the database in hibernate:
1) read configuration
2) get SessionFactory (heavyweight, only one)
3) obtain session
4) start a transaction
5) perform CRUD operation
6) commit transaction
7) close session
In our mybatis, there are similar steps:
1) obtain SqlSessionFactory
2) obtain SqlSession
3) perform CURD operation
4) commit transaction
5) close SqlSession
First of all, let's look at how to obtain SqlSessionFactory. The applicable sequence of each MyBatis takes a real example of an SqlSessionFactory object as the core. A real example of a SqlSessionFactory object can be obtained by passing through a SqlSessionFactoryBuilder object. The SqlSessionFactoryBuilder object can build a SqlSessionFactory object from a XML configuration file or from a custom-prepared instance of the Configuration class.
A quote from an official document. Explain that there are two ways to get SqlSessionFactory, the first is to configure XML through our core, and the second is through the Configuration class
Configure XML mode through the core
Reader reader = Resources.getResourceAsReader ("ibatis-config.xml"); SqlSessionFactory factory = new SqlSessionFactoryBuilder () .build (reader)
Through Configuration (that is, to convert the XML configuration to the corresponding object)
DataSource dataSource =... TransactionFactory transactionFactory = new JdbcTransactionFactory (); Environment environment = new Environment ("development", transactionFactory, dataSource); Configuration configuration = new Configuration (environment); configuration.addMapper (BlogMapper.class); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder (). Build (configuration); get SqlSessionSqlSession sqlSession = factory.openSession (); add tool class
Because there is only one SqlSessionFactory object as the core in our system, we can get SqlSessionFactory and SqlSession through a utility class. It is convenient for program operation.
Package com.yu.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;/** * mybatis utility class * @ author yu * * / public class SqlSessionFactoryUtil {private static String XML_PATH = "mybatis-config.xml"; private static SqlSessionFactory factory Static {Reader r = null; try {r = Resources.getResourceAsReader (XML_PATH); factory = new SqlSessionFactoryBuilder () .build (r);} catch (IOException e) {e.printStackTrace () }} / * obtain SqlSessionFactory * @ return SqlSessionFactory * / public static SqlSessionFactory getSqlSessionFactory () {return factory in the application } / * get SqlSession * @ return SqlSession * / public static SqlSession getSqlSession () {return factory.openSession () in the application } / * close SqlSession * @ param session * / public static void closeSqlSession (SqlSession session) {if (session! = null) {session.close ();} Test Code
With a lot of groundwork in front of me, and now that I can finally run it, I wrote a test class to test the CRUD operation of mybatis in the way of JUnit.
Package com.yu.test;import java.util.List;import org.apache.ibatis.session.SqlSession;import org.junit.After;import org.junit.Before;import org.junit.Test;import com.yu.model.User;import com.yu.util.SqlSessionFactoryUtil;public class MyTest {public SqlSession session; @ Before public void getSqlSession () {session = SqlSessionFactoryUtil.getSqlSession () } @ After public void closeSqlSession () {SqlSessionFactoryUtil.closeSqlSession (session);} @ Test public void queryUser () {List users = session.selectList ("UserMapper.queryUser") For (User u: users) {System.out.println (u.getId () + "+ u.getName ());}} @ Test public void findUserById () {Long id = 1L; User user = session.selectOne (" UserMapper.findUserById ", id) If (username null) {System.out.println (user.getId () + "+ user.getName ());}} @ Test public void findUserByName () {String name =" an "; List users = session.selectList (" UserMapper.findUserByName ", name) For (User u: users) {System.out.println (u.getId () + "+ u.getName ());}} @ Test public void addUser () {User user = new User (); user.setId (10L) User.setName ("pockmarked Wang"); session.insert ("UserMapper.addUser", user); session.commit ();} @ Test public void updateUser () {User user = new User (); user.setId (10L); user.setName ("pockmarked Wang") Session.insert ("UserMapper.updateUser", user); session.commit ();} @ Test public void deleteUser () {Long id = 10L; session.delete ("UserMapper.deleteUser", id); session.commit ();}}
After execution, you can verify that the data is correct by looking at the database.
6. Other questions
The above example completes the basic operation of Mybatis from the core configuration file, to the mapping file, to getting SqlSessionFactory, to getting SqlSession, to java API operation, and then to test verification.
Of course, this is only the most basic usage.
For example, the core configuration here can be configured with the abbreviation of the return type.
For example, the setting of resultType in the mapping file here
For example, the java operation here can also be changed to the operation through the Mapper interface
For example, the mapping configuration here can also be implemented through annotations in the Mapper interface.
Another example is mybatis's dynamic sql, type conversion, interceptor and so on.
Source code: × × / technology
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.