Ibatis learning notes (1) Example

Source: Internet
Author: User
Ibatis learning notes (1) Example

Previously, Hibernate was used more often and may be preemptible. There were fewer persistence layer technologies. Recently, many projects that focus on performance and efficiency are using ibatis, so I have to pay attention to it, sort out a learning summary, starting with a hello World.

1. Create a database

create database sample;use sampledrop table if exists `t_user`;CREATE TABLE `t_user` (  `id` int(11) NOT NULL auto_increment,  `name` varchar(50) default NULL,  `sex` int(2) default NULL,  PRIMARY KEY  (`id`));insert into t_user values(null,'huiming',1),(null,'mingming',0);
View the database as follows:

Now we have prepared the data.

2. Build basic code (1) Configure logs

First, configure the log. Here we use commons_logging to create the log4j. properties configuration file in classpath:

log4j.rootLogger=DEBUG, stdout  log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%c{1} - %m%n  log4j.logger.java.sql.PreparedStatement=DEBUG 

(2) Build a configuration file

The core of ibatis in the configuration file, as shown in:


Sqlmapconfig is the core. Let's take a look at its content:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE sqlMapConfig     PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"     "http://www.ibatis.com/dtd/sql-map-config-2.dtd"><sqlMapConfig><settings cacheModelsEnabled="true" enhancementEnabled="true"lazyLoadingEnabled="true" errorTracingEnabled="true" maxRequests="32"maxSessions="10" maxTransactions="5" useStatementNamespaces="false" /><transactionManager type="JDBC"><dataSource type="SIMPLE"><property name="JDBC.Driver" value="com.mysql.jdbc.Driver" /><property name="JDBC.ConnectionURL"value="jdbc:mysql://localhost/test" /><property name="JDBC.Username" value="root" /><property name="JDBC.Password" value="" /><property name="Pool.MaximumActiveConnections" value="10" /><property name="Pool.MaximumIdleConnections" value="5" /><property name="Pool.MaximumCheckoutTime" value="120000" /><property name="Pool.TimeToWait" value="500" /><property name="Pool.PingQuery"value="select 1 from t_user" /><property name="Pool.PingEnabled" value="false" /><property name="Pool.PingConnectionsOlderThan" value="1" /><property name="Pool.PingConnectionsNotUsedFor" value="1" /></dataSource></transactionManager><sqlMap resource="com/test/maps/User.xml" /></sqlMapConfig>

(1) settings Node

Cachemodelsenabled: whether to enable the cache mechanism on sqlmapclient. We recommend that you set this parameter to "true"
Enhancementenabled: whether to enable the bytecode enhancement mechanism for pojo to improve the call efficiency of getter/setter and avoid the performance overhead caused by javareflect. At the same time, this also brings great performance recommendations for lazy loading to be set to "true"
Whether lazyloadingenabled enables the delayed loading mechanism. We recommend that you set it to "true"
Whether errortracingenabled enables error logs. It is recommended to set it to "true" during development"
Maxrequests maximum number of concurrent requests (statement concurrency)
Maxtransactions maximum number of concurrent transactions
Maxsessions: Maximum number of sessions. That is, the maximum number of concurrent sqlmapclients allowed currently.
Maxsessions must be set between maxtransactions and maxrequests.
Whether usestatementnamespaces uses the statement namespace. The namespace here refers to the namespace attribute of the sqlmap node in the ing file,
For example, in the preceding example, the ing file sqlmap node for the t_user table is:
<Sqlmap namespace = "user">
Here, all operations defined under this sqlmap node belong to the "user" namespace. When usestatementnamespaces = "true,
Statement call requires an additional namespace, such as sqlmap. Update ("user. updateuser", user );
Otherwise, you can call the statement directly by using the statement name, for example, sqlmap. Update ("updateuser", user). The statement definition has no duplicate names.

(2) transactionmanager Node
The transactionmanager node defines the Transaction Manager of ibatis,
JDBC
Transaction support is achieved through traditional JDBC connection. Commit/rollback.

(3) datasource Node

Datasource belongs to the transactionmanager node and is used to set the datasource attribute used during ibatis runtime.

(4) sqlmap Node
The sqlmap node specifies the location of the ing file. Multiple sqlmap nodes may appear in the configuration to specify
All ing files included in the project.

(3) create a model

Create a user model

package com.test.model;import java.io.Serializable;public class User implements Serializable {private static final long serialVersionUID = 1L;private Integer id;private String name;private Integer sex;public User() {}public Integer getId() {return this.id;}public void setId(Integer id) {this.id = id;}public String getName() {return this.name;}public void setName(String name) {this.name = name;}public Integer getSex() {return this.sex;}public void setSex(Integer sex) {this.sex = sex;}}

(4) create a ing File

The ibatis ing file is different from hibernate, because you need to manually write SQL statements.

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE sqlMap     PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"     "http://www.ibatis.com/dtd/sql-map-2.dtd"><sqlMap namespace="User"><typeAlias alias="user" type="com.test.model.User" /><select id="getUser" parameterClass="java.lang.String"resultClass="user"><![CDATA[     select       name,       sex     from t_user     where name = #name#     ]]></select><select id="getAllUser" resultClass="user"><![CDATA[     select       name,       sex     from t_user   where name = #name#      ]]></select><update id="updateUser" parameterClass="user"><![CDATA[     UPDATE t_user     SET        name=#name#,       sex=#sex#   WHERE id = #id# ]]></update><insert id="insertUser" parameterClass="user">INSERT INTO t_user ( name, sex) VALUES ( #name#, #sex# )</insert><delete id="deleteUser" parameterClass="java.lang.String">delete from t_user where id=#value#</delete></sqlMap>

From the preceding ing file, we can see that, through the four nodes <Insert>, <Delete>, <Update>, and <SELECT>, we define the addition, deletion, modification, and query operations for the t_user object respectively.

(4) create a test class

Package COM. test; import Java. SQL. sqlexception; import Java. util. list; import COM. ibatis. sqlmap. client. sqlmapclientbuilder; import COM. test. model. user; public class main {public static void Update () {// first initialize ibatis to obtain a sqlmapclient object string resource = "com/test/maps/sqlmapconfig. XML "; COM. ibatis. sqlmap. client. sqlmapclient sqlmap = NULL; try {Java. io. reader reader = com. ibatis. common. resources. resources. getresourceasreader (Resource); sqlmap = sqlmapclientbuilder. buildsqlmapclient (Reader);} catch (exception e) {e. printstacktrace ();} // After the sqlmap system initialization is complete, execute the update operation try {sqlmap. starttransaction (); User user = new user (); User. setid (New INTEGER (1); User. setname ("Haha"); User. setsex (New INTEGER (1); sqlmap. update ("updateuser", user); sqlmap. committransaction ();} catch (sqlexception e) {system. out. println (E. getmessage ();} finally {try {sqlmap. endtransaction ();} catch (sqlexception e) {e. printstacktrace () ;}} public static list getuser () {// initialize ibatis to obtain a sqlmapclient object string resource = "com/test/maps/sqlmapconfig. XML "; COM. ibatis. sqlmap. client. sqlmapclient sqlmap = NULL; List user = NULL; try {Java. io. reader reader = com. ibatis. common. resources. resources. getresourceasreader (Resource); sqlmap = sqlmapclientbuilder. buildsqlmapclient (Reader);} catch (exception e) {e. printstacktrace ();} // After the sqlmap system initialization is complete, execute the getalluser operation try {sqlmap. starttransaction (); User = sqlmap. queryforlist ("getalluser", "Haha"); sqlmap. committransaction ();} catch (sqlexception e) {system. out. println (E. getmessage ();} finally {try {sqlmap. endtransaction ();} catch (sqlexception e) {e. printstacktrace () ;}} return user;} public static void main (string [] ARGs) {Update (); List user = getuser (); For (INT I = 0; I <user. size (); I ++) {system. out. println (User) user. get (I )). getname ());}}}

3. Test Results

Haha

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.