a complete example of using One to Many and One to One associations using MyBatis annotations

Dear Readers,

Below is a complete example of using One to Many and One to One associations using MyBatis annotations.

Example illustrates how we realized is-a and has-a relation (Candidate is a Person and Candidate has an Address)

PersonDAO & AddressDAO below are simple interfaces to handle CRUD operations. CandidateDAO uses PersonDAO and AddressDAO to realize the association.

view source
print ?
01 package com.examples.dao;
02   
03 import org.apache.ibatis.annotations.CacheNamespace;
04 import org.apache.ibatis.annotations.Delete;
05 import org.apache.ibatis.annotations.Insert;
06 import org.apache.ibatis.annotations.Options;
07 import org.apache.ibatis.annotations.Select;
08 import org.apache.ibatis.annotations.Update;
09   
10 import com.examples.vo.PersonVO;
11   
12 @CacheNamespace(implementation=org.mybatis.caches.ehcache.EhcacheCache.class)
13 public interface PersonDAO {
14   
15     String INSERT_PERSON    = "insert into person (title,firstName,surName,jobTitle,dob,email,mobile,landPhone,fax,twitter,facebook,linkedin) VALUES  (#{title},#{firstName},#{surName},#{jobTitle},#{dob},#{email},#{mobile},#{landPhone},#{fax},#{twitter},#{facebook},#{linkedin})";
16     String UPDATE_PERSON    = "update person set title=#{title},firstName=#{firstName},surName=#{surName},jobTitle=#{jobTitle},dob=#{dob},email=#{email},mobile=#{mobile},landPhone=#{landPhone},fax=#{fax},twitter=#{twitter},facebook=#{facebook},linkedin=#{linkedin} where id=#{id}";
17     String GET_PERSON_BY_ID = "SELECT * FROM vw_person WHERE id = #{personId}";
18     String DELETE_PERSON    = "DELETE FROM person WHERE id = #{personId}";
19   
20     @Select(GET_PERSON_BY_ID)
21     public PersonVO doSelectPerson(long personId) throws Exception;
22   
23     @Update(UPDATE_PERSON)
24     @Options(flushCache=true,useCache=true)
25     public int doUpdatePerson(PersonVO vo) throws Exception;
26   
27     @Insert(INSERT_PERSON)
28     @Options(useGeneratedKeys = true, keyProperty = "id", flushCache=true)
29     public int doCreatePerson(PersonVO person) throws Exception;
30   
31     @Delete(DELETE_PERSON)
32     @Options(flushCache=true)
33     public int doDeletePerson(long personId) throws Exception; 
34   
35 }
view source
print ?
01 package com.examples.dao;
02   
03 import org.apache.ibatis.annotations.CacheNamespace;
04 import org.apache.ibatis.annotations.Delete;
05 import org.apache.ibatis.annotations.Insert;
06 import org.apache.ibatis.annotations.Options;
07 import org.apache.ibatis.annotations.Select;
08 import org.apache.ibatis.annotations.Update;
09   
10 import com.examples.vo.AddressVO;
11   
12 @CacheNamespace(implementation=org.mybatis.caches.ehcache.EhcacheCache.class)
13 public interface AddressDAO{
14   
15     String GET_ADDRESS_BY_ID = "SELECT * FROM vw_address WHERE id = #{addressId}";
16     String INSERT_ADDRESS    = "INSERT into address (building,street,location,town,postCode,countyId,countryId,notes,createdOn,createdBy,active) VALUES (#{building},#{street},#{location},#{town},#{postCode},#{countyId},#{countryId},#{notes},sysdate(),#{createdBy},1)";
17     String UPDATE_ADDRESS    = "UPDATE address set building=#{building},countyId=#{countyId}, street=#{street},location=#{location},town=#{town},postCode=#{postCode},notes=#{notes},modifiedOn=sysdate(),modifiedBy=#{modifiedBy},countryId=#{countryId} where id= #{id}";
18     String DELETE_ADDRESS    = "DELETE from address WHERE id = #{addressId}";
19   
20     @Select(GET_ADDRESS_BY_ID)
21     @Options(useCache=true)
22     public AddressVO doSelectAddress(long addressId) throws Exception;  
23   
24     @Insert(INSERT_ADDRESS)
25     @Options(useGeneratedKeys = true, keyProperty = "id", flushCache=true)
26     public int doCreateAddress(AddressVO address) throws Exception;
27   
28     @Update(UPDATE_ADDRESS)
29     @Options(flushCache=true)
30     public int doUpdateAddress(AddressVO address) throws Exception; 
31   
32     @Delete(DELETE_ADDRESS)
33     @Options(flushCache=true)
34     public int doDeleteAddress(long addressId) throws Exception;
35   
36 }
view source
print ?
01 package com.examples.dao;
02   
03 import java.util.List;
04   
05 import org.apache.ibatis.annotations.CacheNamespace;
06 import org.apache.ibatis.annotations.Delete;
07 import org.apache.ibatis.annotations.Insert;
08 import org.apache.ibatis.annotations.Many;
09 import org.apache.ibatis.annotations.One;
10 import org.apache.ibatis.annotations.Options;
11 import org.apache.ibatis.annotations.Param;
12 import org.apache.ibatis.annotations.Result;
13 import org.apache.ibatis.annotations.Results;
14 import org.apache.ibatis.annotations.Select;
15 import org.apache.ibatis.annotations.Update;
16   
17 import com.examples.vo.AddressVO;
18 import com.examples.vo.CandidateVO;
19 import com.examples.vo.EmployerVO;
20 import com.examples.vo.PersonVO;
21   
22 @CacheNamespace(implementation=org.mybatis.caches.ehcache.EhcacheCache.class)
23 public interface CandidateDAO {
24   
25     String GET_CANDIDATE_BY_ID="select c.* from candidate c where id=#{id} and active=1";  
26   
27     String GET_CANDIDATES_BY_USER_COMPANY = "select * from vw_company_candidate where companyId=#{companyId} and active=1";
28   
29     String GET_CANDIDATE_BY_ID_AND_USER_COMPANY = "select * from vw_company_candidate where companyId=#{companyId} and id=#{candidateId} and active=1";
30   
31     String INSERT_CANDIDATE = "INSERT INTO candidate (" +
32             " personId,addressId,employerId,clientId,basic,ote,met," +
33             " reference,exclusive,createdOn,createdBy,active," +
34             " priority,code,offers,referredBy,statusId,salCurrencyId,salTenureId) " +
35           "VALUES " +
36             " (#{person.id},#{address.id},#{employer.id},#{client.id}," +
37             " #{basic},#{ote},#{met},#{reference}," +
38             " #{exclusive},sysdate(),#{createdBy},1,#{priority}," +
39             " #{code},#{offers},#{referredBy},#{statusId},#{salCurrencyId},#{salTenureId})";
40   
41     String UPDATE_CANDIDATE = "UPDATE candidate SET " +
42             " personId=#{person.id}, addressId=#{address.id}, employerId=#{employer.id}, clientId=#{client.id}," +
43             " basic=#{basic}, ote=#{ote},met=#{met},reference=#{reference}," +
44             " exclusive=#{exclusive},modifiedOn=sysdate(),modifiedBy=#{modifiedBy},active=#{active},priority=#{priority}," +
45             " code=#{code},offers=#{offers},referredBy=#{referredBy},statusId=#{statusId}, " +
46             " salCurrencyId=#{salCurrencyId},salTenureId=#{salTenureId} where id=#{id}";
47   
48     String DELETE_CANDIDATE = "update candidate set active=0 where id=#{candidateId}";
49   
50     String MAP_CANDIDATE_SECTOR = "insert ignore into candidate_sector(sectorId,candidateId) values (#{sectorId},#{candidateId})";
51   
52     @Select(GET_CANDIDATES_BY_USER_COMPANY)
53     @Results(value = {
54         @Result(property="id", column="id"),
55         @Result(property="person",  column="personId",  javaType=PersonVO.class, one=@One(select="com.examples.dao.PersonDAO.doSelectPerson")),
56         @Result(property="address", column="addressId", javaType=AddressVO.class, one=@One(select="com.examples.dao.AddressDAO.doSelectAddress"))
57     })
58     public List doSelectCandidatesByCompany(long companyId);
59   
60     @Select(GET_CANDIDATE_BY_ID)
61     @Results({
62              @Result(property="id",     column="id"),
63              @Result(property="person", column="personId",   javaType=PersonVO.class, one=@One(select="com.examples.dao.PersonDAO.doSelectPerson")),
64              @Result(property="address",column="addressId",  javaType=AddressVO.class, one=@One(select="com.examples.dao.AddressDAO.doSelectAddress")),@Result(property="sectors", column="id",           javaType=List.class,      many=@Many(select = "com.examples.dao.SectorDAO.doSelectSectorsByCandidate"))
65              })
66     public CandidateVO doSelectCandidateById(long candidateId);
67   
68     @Insert(INSERT_CANDIDATE)
69     @Options(useGeneratedKeys = true, keyProperty = "id", flushCache=true)
70     public int doCreateCandidate(CandidateVO candidate) throws Exception;   
71   
72     @Update(UPDATE_CANDIDATE)
73     @Options(flushCache=true)
74     public int doUpdateCandidate(CandidateVO candidate) throws Exception;
75   
76     @Delete(DELETE_CANDIDATE)
77     @Options(flushCache=true)
78     public int doDeleteCandidate(long candidateId) throws Exception;
79   
80     @Insert(MAP_CANDIDATE_SECTOR)
81     public void doMapCandidateSector(@Param("sectorId") long sectorId, @Param("candidateId") long candidateId);
82 }

Explanation to follow …

Did you like this? Share it:

Annotations without associations

Dear Readers,

Below is a very simple example of using mybatis annotations. Personally I support annotations based approach over XML, just for a simple reason that everything is inline and debugging and maintenance found to be easier than with other approaches.

Most annotations are self explanatory. MyBatis is really good in this aspect. We can guess what the annotations functionality is by just having a quick glance.

Well as usual it is up to your requirements and team preferences to choose one over the other.

Below is a simple interface to deal with Address data and it handles CRUD operations.

view source
print ?
01 package com.examples.dao;
02   
03 import org.apache.ibatis.annotations.CacheNamespace;
04 import org.apache.ibatis.annotations.Delete;
05 import org.apache.ibatis.annotations.Insert;
06 import org.apache.ibatis.annotations.Options;
07 import org.apache.ibatis.annotations.Select;
08 import org.apache.ibatis.annotations.Update;
09   
10 import com.examples.vo.AddressVO;
11   
12 @CacheNamespace(implementation=org.mybatis.caches.ehcache.EhcacheCache.class)
13 public interface AddressDAO{
14   
15     String GET_ADDRESS_BY_ID = "SELECT * FROM vw_address WHERE id = #{addressId}";
16     String INSERT_ADDRESS    = "INSERT into address (building,street,location,town,postCode,countyId,countryId,notes,createdOn,createdBy,active) VALUES (#{building},#{street},#{location},#{town},#{postCode},#{countyId},#{countryId},#{notes},sysdate(),#{createdBy},1)";
17     String UPDATE_ADDRESS    = "UPDATE address set building=#{building},countyId=#{countyId}, street=#{street},location=#{location},town=#{town},postCode=#{postCode},notes=#{notes},modifiedOn=sysdate(),modifiedBy=#{modifiedBy},countryId=#{countryId} where id= #{id}";
18     String DELETE_ADDRESS    = "DELETE from address WHERE id = #{addressId}";
19   
20     @Select(GET_ADDRESS_BY_ID)
21     @Options(useCache=true)
22     public AddressVO doSelectAddress(long addressId) throws Exception;  
23   
24     @Insert(INSERT_ADDRESS)
25     @Options(useGeneratedKeys = true, keyProperty = "id", flushCache=true)
26     public int doCreateAddress(AddressVO address) throws Exception;
27   
28     @Update(UPDATE_ADDRESS)
29     @Options(flushCache=true)
30     public int doUpdateAddress(AddressVO address) throws Exception; 
31   
32     @Delete(DELETE_ADDRESS)
33     @Options(flushCache=true)
34     public int doDeleteAddress(long addressId) throws Exception;
35   
36 }

I am using EHCACHE for cache implementations (Have a look at http://www.terracotta.org/ehcache/ to find out more about EHCACHE). Therefore I’ve set the Cache Namespace by using the annotation and indicated that implementation class should be EhcacheCache.class.

view source
print ?
1 @CacheNamespace(implementation=org.mybatis.caches.ehcache.EhcacheCache.class)

In the subsequent lines I declared set of static variables holding SQL queries.

Rest all code is straight forward except the flushCache attribute within @Options annotation

view source
print ?
1 @Options(flushCache=true) //or false

flushCache=true : Indicates that Cache must be flushed after the operation is successfully carried out. In the above example cache is flushed right after @Insert, @Update & @Delete operations.

flushCache=false : Is the opposite as you might have expected by now. By default this option is set to false. You do not need to set this to false explicitly.

All other annotations and attributes are self explanatory I trust. If you find it hard to figure out then please do not hesitate to drop me an email. I will respond to your queries as soon as I can.

Did you like this? Share it:

MyBatis Insert Using Annotations and XML

Dear Readers,

Below is an example of inserting data using mybatis annotations and xml. Both XML and Annotation based inserts should set the newly inserted records id in the given object.

  • Please get the sql scripts from here
  • Please get the classes and required mybatis configuration files from here

** I am using MySQL auto increment functionality for generating the primary key values.

1. Insert using annotations

view source
print ?
01 package com.mybatis.demo.role.dao;
02   
03 import java.util.List;
04   
05 import org.apache.ibatis.annotations.Insert;
06 import org.apache.ibatis.annotations.Options;
07 import com.mybatis.demo.role.vo.RoleVO;
08   
09 public interface RoleDAO {
10     String MQL_CREATE_ROLE    = "insert into roles (roleName, roleDescription) values (#{roleName},#{roleDescription})";
11     @Insert(MQL_CREATE_ROLE)
12     @Options(useGeneratedKeys = true, keyProperty="id")
13     public int doCreateRole(RoleVO vo) throws Exception;
14 }

@Options Annotation

keyProperty
If you have experienced iBatis/ MyBatis Mapping, you might expect a @SelectKey annotation. But the case is slightly different from what you expect it to be. There is a keyProperty attribute under @Options annotation, using which the key property name is identified.
useGeneratedKeys
Attribute specifies that underlying database takes care of generating / auto incrementing the column values. Must be set to true when you are using AutoGenerated field

@Options Annotation
This is pretty straight forward. As usual you will need to pass SQL Query as an argument.

2. Insert Using XML

view source
print ?
01 xml version="1.0" encoding="UTF-8" ?>
02
03 <mapper namespace="com.mybatis.demo.role.dao.RoleDAO">
04      <insert id="insertRole" parameterType="Role"  timeout="20000">
05         
06             insert into roles(rolename,roledescription) values (#{roleName},#{roleDescription})
07         ]]>
08         <selectKey resultType="java.lang.Long" keyProperty="id" >
09             SELECT LAST_INSERT_ID() AS id
10         selectKey>
11      insert>
12 mapper>
LAST_INSERT_ID()
SELECT LAST_INSERT_ID() is MySQL way of selecting the last inserted id from the database. Check out this page for detailed information about this function.
You must be careful to use appropriate database function to get the last inserted value, because this varies from database to database. e.g., In Oracle it is SEQUENCE.NEXTVAL and in MS SQL Server it is @@identity or ident_current()

Rest all tags are self explanatory… I know you are smiling

Did you like this? Share it:

MyBatis one-to-many mapping

Dear Readers,

Let us explore mapping one-to-many relationships with MyBatis. Please note that I am using XML based mapping instead of annotations ( resultMap has been added as an attribute to @Options annotation recently )

I will continue to use the demo schema for all examples.

Just to recap the relation, please find below picture. Each Role has access to One or More Modules, which is a One-To-Many relation between role table and module table. The relation between Role Table and Module Table is realized by the third mapping table Role_Module.

Role Module Mapping

1. XML Mapping File

view source
print ?
01 xml version="1.0" encoding="UTF-8" ?>
02
03 <mapper namespace="com.mybatis.demo.role.dao.RoleDAO">  
04   
05      <resultMap id="RoleMap" type="Role">
06          <id property="id" column="r_id" />
07          <result property="roleName" column="rolename" />
08          <result property="roleDescription" column="roledescription" />
09          <collection property="modules" column="rm_id" ofType="Module" javaType="ArrayList" resultMap="ModuleMap"/>
10      resultMap>
11   
12      <resultMap id="ModuleMap" type="Module">
13         <id property="id" column="m_id" />
14         <result property="moduleName" column="modulename" />
15         <result property="moduleDescription" column="moduledescription" />
16      resultMap>
17   
18      <select id="getRoles" resultMap="RoleMap" >
19         select
20             r.id as r_id , r.rolename, r.roledescription,
21             m.id as m_id, modulename, moduledescription,
22             rm.id as rm_id, rm.roleid, rm.moduleid
23         from roles r
24             left outer join role_module rm on r.id=rm.roleid
25             left outer join modules m on m.id= rm.moduleid
26      select
27   
28 mapper>

2. RoleVO Class

view source
print ?
001 /**
002  *
003  */
004 package com.mybatis.demo.role.vo;
005   
006 import java.io.Serializable;
007 import java.util.ArrayList;
008 import java.util.List;
009   
010 import com.mybatis.demo.base.vo.BaseVO;
011 import com.mybatis.demo.module.vo.ModuleVO;
012   
013 /**
014  * @author gowri
015  *
016  */
017 public class RoleVO implements Serializable, BaseVO {
018   
019     private static final long serialVersionUID = -3563604377383689069L;
020   
021     private long id;
022     private String roleName;
023     private String roleDescription;
024   
025     private List modules =new ArrayList();
026   
027     /* (non-Javadoc)
028      * @see com.mybatis.demo.base.vo.BaseVO#getId()
029      */
030     @Override
031     public long getId() {
032         return id;
033     }
034   
035     /* (non-Javadoc)
036      * @see com.mybatis.demo.base.vo.BaseVO#setId(long)
037      */
038     @Override
039     public void setId(long id) {
040         this.id=id;
041   
042     }
043   
044     /**
045      * @return the roleName
046      */
047     public String getRoleName() {
048         return roleName;
049     }
050   
051     /**
052      * @param roleName the roleName to set
053      */
054     public void setRoleName(String roleName) {
055         this.roleName = roleName;
056     }
057   
058     /**
059      * @return the roleDescription
060      */
061     public String getRoleDescription() {
062         return roleDescription;
063     }
064   
065     /**
066      * @param roleDescription the roleDescription to set
067      */
068     public void setRoleDescription(String roleDescription) {
069         this.roleDescription = roleDescription;
070     }
071   
072     /* (non-Javadoc)
073      * @see java.lang.Object#hashCode()
074      */
075     @Override
076     public int hashCode() {
077         final int prime = 31;
078         int result = 1;
079         result = prime * result + (int) (id ^ (id >>> 32));
080         result = prime * result
081                 + ((roleName == null) ? 0 : roleName.hashCode());
082         return result;
083     }
084   
085     /* (non-Javadoc)
086      * @see java.lang.Object#equals(java.lang.Object)
087      */
088     @Override
089     public boolean equals(Object obj) {
090         if (this == obj)
091             return true;
092         if (obj == null)
093             return false;
094         if (getClass() != obj.getClass())
095             return false;
096         RoleVO other = (RoleVO) obj;
097         if (id != other.id)
098             return false;
099         if (roleName == null) {
100             if (other.roleName != null)
101                 return false;
102         } else if (!roleName.equals(other.roleName))
103             return false;
104         return true;
105     }
106   
107     /**
108      * @return the modules
109      */
110     public List getModules() {
111         return modules;
112     }
113   
114     /**
115      * @param modules the modules to set
116      */
117     public void setModules(List modules) {
118         this.modules = modules;
119     }
120   
121     /* (non-Javadoc)
122      * @see java.lang.Object#toString()
123      */
124     @Override
125     public String toString() {
126         StringBuilder builder = new StringBuilder();
127         builder.append("RoleVO [id=");
128         builder.append(id);
129         builder.append(", modules=");
130         builder.append(modules);
131         builder.append(", roleDescription=");
132         builder.append(roleDescription);
133         builder.append(", roleName=");
134         builder.append(roleName);
135         builder.append("]");
136         return builder.toString();
137     }
138   
139 }

3. ModuleVO Class

view source
print ?
001 package com.mybatis.demo.module.vo;
002   
003 import java.io.Serializable;
004   
005 import com.mybatis.demo.base.vo.BaseVO;
006   
007 public class ModuleVO implements Serializable, BaseVO {
008   
009     private static final long serialVersionUID = 7925494461319098443L;
010   
011     private long id;
012     private String moduleName;
013     private String moduleDescription;
014   
015     @Override
016     public long getId() {
017                 return id;
018     }
019   
020     @Override
021     public void setId(long id) {
022         this.id=id;
023     }
024   
025     /**
026      * @return the moduleName
027      */
028     public String getModuleName() {
029         return moduleName;
030     }
031   
032     /**
033      * @param moduleName the moduleName to set
034      */
035     public void setModuleName(String moduleName) {
036         this.moduleName = moduleName;
037     }
038   
039     /**
040      * @return the moduleDescription
041      */
042     public String getModuleDescription() {
043         return moduleDescription;
044     }
045   
046     /**
047      * @param moduleDescription the moduleDescription to set
048      */
049     public void setModuleDescription(String moduleDescription) {
050         this.moduleDescription = moduleDescription;
051     }
052   
053     /* (non-Javadoc)
054      * @see java.lang.Object#toString()
055      */
056     @Override
057     public String toString() {
058         StringBuilder builder = new StringBuilder();
059         builder.append("ModuleVO [id=");
060         builder.append(id);
061         builder.append(", moduleDescription=");
062         builder.append(moduleDescription);
063         builder.append(", moduleName=");
064         builder.append(moduleName);
065         builder.append("]");
066         return builder.toString();
067     }
068   
069     /* (non-Javadoc)
070      * @see java.lang.Object#hashCode()
071      */
072     @Override
073     public int hashCode() {
074         final int prime = 31;
075         int result = 1;
076         result = prime * result + (int) (id ^ (id >>> 32));
077         result = prime * result
078                 + ((moduleName == null) ? 0 : moduleName.hashCode());
079         return result;
080     }
081   
082     /* (non-Javadoc)
083      * @see java.lang.Object#equals(java.lang.Object)
084      */
085     @Override
086     public boolean equals(Object obj) {
087         if (this == obj)
088             return true;
089         if (obj == null)
090             return false;
091         if (getClass() != obj.getClass())
092             return false;
093         ModuleVO other = (ModuleVO) obj;
094         if (id != other.id)
095             return false;
096         if (moduleName == null) {
097             if (other.moduleName != null)
098                 return false;
099         } else if (!moduleName.equals(other.moduleName))
100             return false;
101         return true;
102     }
103   
104 }
Did you like this? Share it:

MyBatis Simple and Complete Example

This is a failry simple example using MyBatis Annotations. Good one to start with to get an overall view of how MyBatis makes things simplier, easier and faster.

Please notice the main method in UserBO class. All you need to do to test this example is, just run that class.

1. database.properties

view source
print ?
1 database.driver=com.mysql.jdbc.Driver
2 database.url=jdbc:mysql://localhost:3306/database_name
3 database.username= ************
4 database.password= ************

2. configuration.xml

view source
print ?
01 <configuration>
02     <properties resource="database.properties"/>
03     <environments default="development">
04         <environment id="development">
05             <transactionManager type="JDBC"/>
06             <dataSource type="POOLED">
07                 <property name="driver" value="${database.driver}"/>
08                 <property name="url" value="${database.url}"/>
09                 <property name="username" value="${database.username}"/>
10                 <property name="password" value="${database.password}"/>
11             dataSource>
12         environment>
13     environments>
14     <mappers>
15         <mapper resource="com/mybatis/demo/user/UserMapper.xml"/>
16     mappers>
17 configuration>

3. UserMapper.xml

view source
print ?
1 xml version="1.0" encoding="UTF-8" ?>
2
3     PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
4     "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
5 <mapper namespace="com.mybatis.demo.user.dao.UserDAO">mapper>

4. ConnectionFactory Class

view source
print ?
01 package com.mybatis.demo;
02   
03 import java.io.Reader;
04 import org.apache.ibatis.io.Resources;
05 import org.apache.ibatis.session.SqlSessionFactory;
06 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
07   
08 public class ConnectionFactory {
09   
10     private static SqlSessionFactory sqlMapper;
11     private static Reader reader; 
12   
13     static{
14         try{
15             reader    = Resources.getResourceAsReader("configuration.xml");
16             sqlMapper = new SqlSessionFactoryBuilder().build(reader);
17         }catch(Exception e){
18             e.printStackTrace();
19         }
20     }
21   
22     public static SqlSessionFactory getSession(){
23         return sqlMapper;
24     }
25 }

5. UserVO Class

view source
print ?
001 package com.mybatis.demo.user.vo;
002   
003 import java.io.Serializable;
004   
005 import com.mybatis.demo.base.vo.BaseVO;
006   
007 public class UserVO implements Serializable, BaseVO {
008   
009     private static final long serialVersionUID = 4872640461000241018L;
010   
011     private long id;
012     private String fullName;
013     private String address;
014     private String email;
015     private String mobile;
016   
017     @Override
018     public long getId(){
019          return this.id;
020     }
021   
022     @Override
023     public void setId(long id) {
024         this.id=id;
025     }
026   
027     /**
028      * @return the fullName
029      */
030     public String getFullName() {
031         return fullName;
032     }
033   
034     /**
035      * @param fullName the fullName to set
036      */
037     public void setFullName(String fullName) {
038         this.fullName = fullName;
039     }
040   
041     /**
042      * @return the address
043      */
044     public String getAddress() {
045         return address;
046     }
047   
048     /**
049      * @param address the address to set
050      */
051     public void setAddress(String address) {
052         this.address = address;
053     }
054   
055     /**
056      * @return the email
057      */
058     public String getEmail() {
059         return email;
060     }
061   
062     /**
063      * @param email the email to set
064      */
065     public void setEmail(String email) {
066         this.email = email;
067     }
068   
069     /**
070      * @return the mobile
071      */
072     public String getMobile() {
073         return mobile;
074     }
075   
076     /**
077      * @param mobile the mobile to set
078      */
079     public void setMobile(String mobile) {
080         this.mobile = mobile;
081     }
082   
083     /* (non-Javadoc)
084      * @see java.lang.Object#toString()
085      */
086     @Override
087     public String toString() {
088         StringBuilder builder = new StringBuilder();
089         builder.append("UserVO [address=");
090         builder.append(address);
091         builder.append(", email=");
092         builder.append(email);
093         builder.append(", fullName=");
094         builder.append(fullName);
095         builder.append(", id=");
096         builder.append(id);
097         builder.append(", mobile=");
098         builder.append(mobile);
099         builder.append("]");
100         return builder.toString();
101     }
102   
103     /* (non-Javadoc)
104      * @see java.lang.Object#hashCode()
105      */
106     @Override
107     public int hashCode() {
108         final int prime = 31;
109         int result = 1;
110         result = prime * result
111                 + ((fullName == null) ? 0 : fullName.hashCode());
112         result = prime * result + (int) (id ^ (id >>> 32));
113         return result;
114     }
115   
116     /* (non-Javadoc)
117      * @see java.lang.Object#equals(java.lang.Object)
118      */
119     @Override
120     public boolean equals(Object obj) {
121         if (this == obj)
122             return true;
123         if (obj == null)
124             return false;
125         if (getClass() != obj.getClass())
126             return false;
127         UserVO other = (UserVO) obj;
128         if (fullName == null) {
129             if (other.fullName != null)
130                 return false;
131         } else if (!fullName.equals(other.fullName))
132             return false;
133         if (id != other.id)
134             return false;
135         return true;
136     }
137 }

6. UserDAO Interface

view source
print ?
01 package com.mybatis.demo.user.dao;
02   
03 import java.util.List;
04   
05 import org.apache.ibatis.annotations.Delete;
06 import org.apache.ibatis.annotations.Insert;
07 import org.apache.ibatis.annotations.Select;
08 import org.apache.ibatis.annotations.Update;
09   
10 import com.mybatis.demo.user.vo.UserVO;
11   
12 public interface UserDAO {
13   
14     String MQL_GET_ALL_USERS  = "select * from users";
15     String MQL_GET_USER_BY_ID = "select * from users where id = #{id}";
16     String MQL_CREATE_USER    = "insert into users (fullName, email, address, mobile) values (#{fullName},#{email},#{address},#{mobile})";
17     String MQL_UPDATE_USER    = "update users set fullName=#{fullName}, email=#{email}, address=#{address}, mobile=#{mobile} where id=#{id}";
18     String MQL_DELETE_USER    = "delete from users where id=#{id}";
19   
20     @Select(MQL_GET_ALL_USERS)
21     public List getAllUsers() throws Exception;
22   
23     @Select(MQL_GET_USER_BY_ID)
24     public UserVO getUserById(long id) throws Exception;
25   
26     @Insert(MQL_CREATE_USER)
27     public int doCreateUser(UserVO vo) throws Exception;
28   
29     @Update(MQL_UPDATE_USER)
30     public int doUpdateUser(UserVO vo) throws Exception; 
31   
32     @Delete(MQL_DELETE_USER)
33     public int doDeleteUser(UserVO vo) throws Exception;  
34   
35 }

7. UserBO Class

view source
print ?
01 package com.mybatis.demo.user.bo;
02   
03 import java.util.List;
04   
05 import org.apache.ibatis.session.SqlSession;
06   
07 import com.mybatis.demo.ConnectionFactory;
08 import com.mybatis.demo.user.dao.UserDAO;
09 import com.mybatis.demo.user.vo.UserVO;
10   
11 public class UserBO { 
12   
13     public List getUsers() throws Exception{
14         SqlSession session = ConnectionFactory.getSession().openSession();
15             UserDAO dao =session.getMapper(UserDAO.class);
16             List users= dao.getAllUsers();
17         session.close();
18         return users;
19     }
20     public UserVO getUserById(long id) throws Exception{
21         SqlSession session = ConnectionFactory.getSession().openSession();
22             UserDAO dao =session.getMapper(UserDAO.class);
23             UserVO user =dao.getUserById(id);
24         session.close();
25         return user;
26     }
27     public UserVO createUser(UserVO vo) throws Exception{
28         SqlSession session = ConnectionFactory.getSession().openSession();
29             UserDAO dao =session.getMapper(UserDAO.class);
30             dao.doCreateUser(vo);
31         session.commit();
32         session.close();
33         return vo;
34     }
35     public UserVO updateUser(UserVO vo) throws Exception{
36         SqlSession session = ConnectionFactory.getSession().openSession();
37             UserDAO dao =session.getMapper(UserDAO.class);
38             dao.doUpdateUser(vo);
39         session.commit();
40         session.close();
41         return vo;
42     }
43     public int deleteUser(UserVO vo) throws Exception{
44         SqlSession session = ConnectionFactory.getSession().openSession();
45             UserDAO dao =session.getMapper(UserDAO.class);
46             int cnt= dao.doDeleteUser(vo);
47         session.commit();
48         session.close();
49         return cnt;
50     }
51   
52     public static void main(String a[])throws Exception{
53   
54         UserBO bo = new UserBO();
55         UserVO vo= new UserVO();
56   
57         vo.setAddress("Test");
58         vo.setEmail("[email protected]");
59         vo.setFullName("Full Name");
60         vo.setMobile("12411515");
61   
62         System.out.println(bo.createUser(vo));
63         System.out.println(bo.getUsers());
64   
65         vo= bo.getUserById(1);
66         vo.setAddress("Test Updated11 Address");
67         vo.setEmail("[email protected]");
68         vo.setFullName("Full Name Test");
69         vo.setMobile("1241151511");
70         bo.updateUser(vo);
71   
72         vo=bo.getUserById(1);
73   
74         System.out.println(vo);
75   
76         bo.deleteUser(vo);
77   
78     }
79 }
Did you like this? Share it:

MyBatis Configuration

1. Download MyBatis3.0.2

I am using MyBatis3.0.2 to demonstrate all example in this blog.

Click here to download MyBatis3.0.2

Extract the zip file and place mybatis-3.0.2.jar under libraries (or) in your class path

2. Create a demo database. We explore MyBatis examples using this database.

You can find mybatis demo database scripts here:

http://mybatis.co.uk/index.php/2010/09/mybatis-example-schema.html

Copy and execute the sql scripts and get your demo database ready to start experimenting mybatis.

3. database.properties file contents

view source
print ?
1 database.driver=com.mysql.jdbc.Driver
2 database.url=jdbc:mysql://localhost:3306/database_name
3 database.username= ************
4 database.password= ************

4. configuration.xml file contents

view source
print ?
01 <configuration>
02     <properties resource="database.properties"/>
03     <environments default="development">
04         <environment id="development">
05             <transactionManager type="JDBC"/>
06             <dataSource type="POOLED">
07                 <property name="driver" value="${database.driver}"/>
08                 <property name="url" value="${database.url}"/>
09                 <property name="username" value="${database.username}"/>
10                 <property name="password" value="${database.password}"/>
11             dataSource>
12         environment>
13     environments>
14     <mappers>
15         <mapper resource="com/mybatis/demo/user/UserMapper.xml"/>
16     mappers>
17 configuration>

Take a look at my project explorer, this explains where I placed configuration files (Well, its up to you on how you organize your code )

MyBatisDemoProject Configuration

5. Obtaining MyBatis Session

view source
print ?
01 import org.apache.ibatis.io.Resources;
02 import org.apache.ibatis.session.SqlSessionFactory;
03 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
04   
05 public class ConnectionFactory {
06   
07     private static SqlSessionFactory sqlMapper;
08     private static Reader reader; 
09   
10     static{
11         try{
12             reader    = Resources.getResourceAsReader("configuration.xml");
13             sqlMapper = new SqlSessionFactoryBuilder().build(reader);
14         }catch(Exception e){
15             e.printStackTrace();
16         }
17     }
18   
19     public static SqlSessionFactory getSession(){
20         return sqlMapper;
21     }
22 }
Did you like this? Share it:

MyBatis Example Schema

Dear Readers,

All examples in this blog will be based on the schema below. I’ve chosen MySQL to demonstrate MyBatis examples, as it is fun, fast, lightweight, easy to setup and use.

MyBatis Demo Database Schema

Please find below sql script. Copy and paste to get going

view source
print ?
001 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
002 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
003 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';
004   
005 CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
006 CREATE SCHEMA IF NOT EXISTS `mybatis_demodb` DEFAULT CHARACTER SET latin1 ;
007 USE `mydb` ;
008 USE `mybatis_demodb` ;
009   
010 -- -----------------------------------------------------
011 -- Table `mybatis_demodb`.`users`
012 -- -----------------------------------------------------
013 CREATE  TABLE IF NOT EXISTS `mybatis_demodb`.`users` (
014   `id` INT(8) NOT NULL AUTO_INCREMENT ,
015   `fullname` VARCHAR(50) NOT NULL ,
016   `address` VARCHAR(100) NULL DEFAULT NULL ,
017   `email` VARCHAR(60) NULL DEFAULT NULL ,
018   `mobile` VARCHAR(15) NULL DEFAULT NULL ,
019   PRIMARY KEY (`id`) )
020 ENGINE = InnoDB
021 DEFAULT CHARACTER SET = latin1;
022   
023 -- -----------------------------------------------------
024 -- Table `mybatis_demodb`.`address`
025 -- -----------------------------------------------------
026 CREATE  TABLE IF NOT EXISTS `mybatis_demodb`.`address` (
027   `id` INT(11) NOT NULL AUTO_INCREMENT ,
028   `userid` INT(11) NOT NULL ,
029   `street` VARCHAR(50) NULL DEFAULT NULL ,
030   `city` VARCHAR(50) NULL DEFAULT NULL ,
031   `county` VARCHAR(50) NULL DEFAULT NULL ,
032   `postcode` INT(50) NULL DEFAULT NULL ,
033   `users_id` INT(8) NOT NULL ,
034   PRIMARY KEY (`id`) ,
035   INDEX `fk_user_address` (`userid` ASC) ,
036   INDEX `fk_address_users1` (`users_id` ASC) ,
037   CONSTRAINT `fk_address_users1`
038     FOREIGN KEY (`users_id` )
039     REFERENCES `mybatis_demodb`.`users` (`id` )
040     ON DELETE NO ACTION
041     ON UPDATE NO ACTION)
042 ENGINE = InnoDB
043 DEFAULT CHARACTER SET = latin1;
044   
045 -- -----------------------------------------------------
046 -- Table `mybatis_demodb`.`modules`
047 -- -----------------------------------------------------
048 CREATE  TABLE IF NOT EXISTS `mybatis_demodb`.`modules` (
049   `id` INT(11) NOT NULL AUTO_INCREMENT ,
050   `modulename` VARCHAR(50) NOT NULL ,
051   `moduledescription` VARCHAR(100) NULL DEFAULT NULL ,
052   PRIMARY KEY (`id`) )
053 ENGINE = InnoDB
054 DEFAULT CHARACTER SET = latin1;
055   
056 -- -----------------------------------------------------
057 -- Table `mybatis_demodb`.`roles`
058 -- -----------------------------------------------------
059 CREATE  TABLE IF NOT EXISTS `mybatis_demodb`.`roles` (
060   `id` INT(11) NOT NULL AUTO_INCREMENT ,
061   `rolename` VARCHAR(50) NOT NULL ,
062   `roledescription` VARCHAR(100) NULL DEFAULT NULL ,
063   PRIMARY KEY (`id`) )
064 ENGINE = InnoDB
065 DEFAULT CHARACTER SET = latin1;
066   
067 -- -----------------------------------------------------
068 -- Table `mybatis_demodb`.`role_module`
069 -- -----------------------------------------------------
070 CREATE  TABLE IF NOT EXISTS `mybatis_demodb`.`role_module` (
071   `id` INT(11) NOT NULL ,
072   `roleid` INT(11) NOT NULL ,
073   `moduleid` INT(11) NOT NULL ,
074   PRIMARY KEY (`id`) ,
075   INDEX `fk_module` (`moduleid` ASC) ,
076   INDEX `fk_role` (`roleid` ASC) ,
077   CONSTRAINT `fk_role`
078     FOREIGN KEY (`roleid` )
079     REFERENCES `mybatis_demodb`.`roles` (`id` )
080     ON DELETE CASCADE
081     ON UPDATE CASCADE,
082   CONSTRAINT `fk_module`
083     FOREIGN KEY (`moduleid` )
084     REFERENCES `mybatis_demodb`.`modules` (`id` )
085     ON DELETE CASCADE
086     ON UPDATE CASCADE)
087 ENGINE = InnoDB
088 DEFAULT CHARACTER SET = latin1;
089   
090 -- -----------------------------------------------------
091 -- Table `mybatis_demodb`.`user_role`
092 -- -----------------------------------------------------
093 CREATE  TABLE IF NOT EXISTS `mybatis_demodb`.`user_role` (
094   `id` INT(11) NOT NULL ,
095   `userid` INT(11) NOT NULL ,
096   `roleid` INT(11) NOT NULL ,
097   `users_id` INT(8) NOT NULL ,
098   `roles_id` INT(11) NOT NULL ,
099   PRIMARY KEY (`id`) ,
100   INDEX `fk_user_role_users1` (`users_id` ASC) ,
101   INDEX `fk_user_role_roles1` (`roles_id` ASC) ,
102   CONSTRAINT `fk_user_role_users1`
103     FOREIGN KEY (`users_id` )
104     REFERENCES `mybatis_demodb`.`users` (`id` )
105     ON DELETE NO ACTION
106     ON UPDATE NO ACTION,
107   CONSTRAINT `fk_user_role_roles1`
108     FOREIGN KEY (`roles_id` )
109     REFERENCES `mybatis_demodb`.`roles` (`id` )
110     ON DELETE NO ACTION
111     ON UPDATE NO ACTION)
112 ENGINE = InnoDB
113 DEFAULT CHARACTER SET = latin1;
114   
115 SET SQL_MODE=@OLD_SQL_MODE;
116 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
117 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

你可能感兴趣的:(ORM,Tech)