[Mybatis] add, delete, modify, and query using Mybatis interface programming method.
Original works of Lin bingwen Evankaka. Reprinted please indicate the source http://blog.csdn.net/evankaka
In the previous chapter [Mybatis], the introduction to Mybatis and the addition, deletion, modification, and query of the Mybatis instance have been implemented. The eclipse, mybatis, and mysql environment has been set up, and a simple query has been implemented. Note that this method uses the SqlSession instance to directly execute the ing SQL statement:
session.selectOne("com.mucfc.model.EmployeerMapper.findEmployeerByID", 1);
In fact, there are still simpler methods and better methods, using interfaces that reasonably describe parameters and return values of SQL statements (such as EmployeerMapper. java), so that the code is simpler and safer now, and there are no string text and conversion errors. the detailed process is as follows:
This article will be changed to interface class for addition, deletion, modification, and query
Entire project directory:
Download the sample project in this article for free
1, first or mybatis configuration file mybatis-config.xml
<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE configurationPUBLIC "-// mybatis.org//DTD Config 3.0 //" http://mybatis.org/dtd/mybatis-3-config.dtd "> <! -- This is the root tag --> <configuration> <! -- The element allows a file in the properties format to be provided out of the main configuration file, so that the winner configuration file is more common. This is useful for deployment --> <properties resource = "mysql. properties"/> <! -- Set the alias, which must be placed under properties --> <typeAliases> <typeAlias alias = "Employeer" type = "com. mucfc. model. Employeer"/> </typeAliases> <! -- Configure data source information --> <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/test? CharacterEncoding = UTF-8 "/> <property name =" username "value =" root "/> <property name =" password "value =" christmas258 @ "/> --> <property name = "driver" value = "$ {driver}"/> <property name = "url" value = "$ {url}"/> <property name = "username" value = "$ {username}"/> <property name = "password" value = "$ {password}"/> </dataSource> </environment> </environments> <! -- List ing files --> <mappers> <mapper resource = "com/mucfc/model/Employeer. xml"/> </mappers> </configuration>
The configuration file mysql. properties
driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/test?charset=utf8username=rootpassword=christmas258@
2. Employeer. JAVA
Package com. mucfc. model; import java. io. serializable;/*** employee information class * @ author linbingwen * @ time 2015.5.11 */public class Employeer {private Integer employeer_id; private String employeer_name; private Integer employeer_age; private String employeer_department; private String employeer_worktype; public Employeer () {super ();} public Integer getEmployeer_id () {return employeer_id;} public void setEmployeer_id (Integer employeer_id) {this. employeer_id = employeer_id;} public String getEmployeer_name () {return employeer_name;} public void setEmployeer_name (String employeer_name) {this. employeer_name = employeer_name;} public Integer getEmployeer_age () {return employeer_age;} public void setEmployeer_age (Integer employeer_age) {this. employeer_age = employeer_age;} public String getEmployeer_department () {return employeer_department;} public void setEmployeer_department (String employeer_department) {this. employeer_department = employeer_department;} public String getEmployeer_worktype () {return employeer_worktype;} public void setEmployeer_worktype (String employeer_worktype) {this. response = Response ;}@ Overridepublic String toString () {return "Employeer [employeer_id =" + employeer_id + ", employeer_name =" + employeer_name + ", response =" + employeer_age + ", employeer_department = "+ employeer_department +", employeer_worktype = "+ employeer_worktype +"] ";}}
Then, configure Employeer. xml for the SQL statement:
<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapper PUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <mapper namespace =" com. mucfc. mapper. EmployeerMapper "> <! -- Search --> <select id = "findEmployeerByID" parameterType = "int" resultType = "Employeer"> select * from 't_employeer 'where employeer_id =#{ employeer_id} </select> <! -- Insert --> <! -- UseGeneratedKeys: "true" indicates that MyBatis is required to obtain the primary key automatically generated by the database; keyProperty = "id" specifies to inject the obtained primary key value to the id attribute of Employeer --> <insert id = "addEmployeer" parameterType = "Employeer" useGeneratedKeys = "true" keyProperty =" employeer_id "> insert into 't_ employeer '(employeer_name, employeer_age, employeer_department, Department) values (# {employeer_name}, # {employeer_age}, # {employeer_department}, # {employeer_worktype}) </insert> <! -- Delete --> <delete id = "deleteEmployeer" parameterType = "int"> delete from 't_ employeer 'where employeer_id =#{ employeer_id} </delete> <! -- Modify --> <update id = "updateEmployeer" parameterType = "Employeer"> update t_employeer set employeer_name =#{ employeer_name}, employeer_age =#{ employeer_age }, employeer_department =#{ employeer_department}, employeer_worktype =#{ employeer_worktype} where employeer_id =#{ employeer_id} </update> </mapper>
Note: com. mucfc. mapper. employeerMapper is an interface class. In the previous section, we used com. mucfc. model. employeerMapper, but the class mentioned above does not exist
4. SQL statement ing Class EmployeerMapper. java
Package com. mucfc. mapper; import com. mucfc. model. employeer;/*** SQL statement ing Class * @ author linbingwen * @ time 2015.5.11 */public interface EmployeerMapper {/*** note that Employeer and Employeer are required. the xml method name corresponds to */public Employeer findEmployeerByID (int id);/*** it must be consistent with Employeer. the method name in xml corresponds to */public void addEmployeer (Employeer employeer);/*** it must be consistent with Employeer. the method name in xml corresponds to */public void deleteEmployeer (int id);/*** must be consistent with Employeer. xml method name corresponds to */public void updateEmployeer (Employeer employeer );}
5. test:
(1) Add commands
In the previous section, "Mybatis" is an overview of Mybatis and how to add, delete, modify, and query a Mybatis instance:
/*** Added */public static void addEmployeer (Employeer employeer) {SqlSession session = null; try {session = sqlSessionFactory. openSession (); // the return value is the number of records int resultCount = session. insert ("com. mucfc. model. employeerMapper. addEmployeer ", employeer); System. out. printf ("currently inserted employeer_id: % d number of items currently inserted into the database: % d", employeer. getEmployeer_id (), resultCount); // obtain the id System of the inserted object. out. println (""); session. commit ();} finally {session. close ();}}
Changed to interface programming:
/*** Added */public static void addEmployeer (Employeer employeer) {SqlSession session = null; try {session = sqlSessionFactory. openSession (); EmployeerMapper employeerMapper = session. getMapper (EmployeerMapper. class); employeerMapper. addEmployeer (employeer); session. commit ();} finally {session. close ();}}
(2) Delete commands
In the previous section, "Mybatis" is an overview of Mybatis and how to add, delete, modify, and query a Mybatis instance:
/*** Delete **/public static void deleteEmployeer (int id) {SqlSession session = null; try {session = sqlSessionFactory. openSession (); // the return value is the number of records int resultCount = session. delete ("com. mucfc. model. employeerMapper. deleteEmployeer ", id); System. out. println ("number of items in the current deleted Database:" + resultCount); // gets the id session of the inserted object. commit ();} finally {session. close ();}}
Changed to interface programming:
/*** Delete **/public static void deleteEmployeer (int id) {SqlSession session = null; try {session = sqlSessionFactory. openSession (); EmployeerMapper employeerMapper = session. getMapper (EmployeerMapper. class); employeerMapper. deleteEmployeer (id); session. commit ();} finally {session. close ();}}
(3) Search for commands
In the previous section, "Mybatis" is an overview of Mybatis and how to add, delete, modify, and query a Mybatis instance:
/*** Search for */public static void findEmployeerById (int id) {SqlSession session = null; try {session = sqlSessionFactory. openSession (); Employeer employeer = (Employeer) session. selectOne ("com. mucfc. model. employeerMapper. findEmployeerByID ", 1); if (employeer = null) System. out. println ("null"); elseSystem. out. println (employeer);} finally {session. close ();}}
Changed to interface programming:
/*** Search for */public static void findEmployeerById (int id) {SqlSession session = null; try {session = sqlSessionFactory. openSession (); EmployeerMapper employeerMapper = session. getMapper (EmployeerMapper. class); Employeer employeer = employeerMapper. findEmployeerByID (id); if (employeer = null) System. out. println ("null"); elseSystem. out. println (employeer);} finally {session. close ();}}
(4) Modify commands
In the previous section, "Mybatis" is an overview of Mybatis and how to add, delete, modify, and query a Mybatis instance:
/*** Change */public static void updateEmployeer (Employeer employeer) {SqlSession session = null; try {session = sqlSessionFactory. openSession (); session. update ("com. mucfc. model. employeerMapper. updateEmployeer ", employeer); session. commit ();} finally {session. close ();}}
Changed to interface programming:
/*** Change */public static void updateEmployeer (Employeer employeer) {SqlSession session = null; try {session = sqlSessionFactory. openSession (); EmployeerMapper employeerMapper = session. getMapper (EmployeerMapper. class); employeerMapper. updateEmployeer (employeer); session. commit ();} finally {session. close ();}}
This is a complete test:
Package com. mucfc. test; 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; import com. mucfc. mapper. employeerMapper; import com. mucfc. model. employeer; public class MybatisTest {private static SqlSessionFactory sqlSessionFactory; private static Reader reader; static {try {reader = Resources. getResourceAsReader ("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder (). build (reader);} catch (Exception e) {e. printStackTrace () ;}}/*** search for */public static void findEmployeerById (int id) {SqlSession session = null; try {session = sqlSessionFactory. openSession (); EmployeerMapper employeerMapper = session. getMapper (EmployeerMapper. class); Employeer employeer = employeerMapper. findEmployeerByID (id); if (employeer = null) System. out. println ("null"); elseSystem. out. println (employeer);} finally {session. close () ;}}/*** added */public static void addEmployeer (Employeer employeer) {SqlSession session = null; try {session = sqlSessionFactory. openSession (); EmployeerMapper employeerMapper = session. getMapper (EmployeerMapper. class); employeerMapper. addEmployeer (employeer); session. commit ();} finally {session. close () ;}/ *** Delete **/public static void deleteEmployeer (int id) {SqlSession session = null; try {session = sqlSessionFactory. openSession (); EmployeerMapper employeerMapper = session. getMapper (EmployeerMapper. class); employeerMapper. deleteEmployeer (id); session. commit ();} finally {session. close () ;}/ *** change */public static void updateEmployeer (Employeer employeer) {SqlSession session = null; try {session = sqlSessionFactory. openSession (); EmployeerMapper employeerMapper = session. getMapper (EmployeerMapper. class); employeerMapper. updateEmployeer (employeer); session. commit ();} finally {session. close () ;}} public static void main (String [] args) {Employeer employeer1 = new Employeer (); employeer1.setEmployeer _ name ("Li Si "); worker _ age (23); employeer1.setEmployeer _ department ("Product 1"); employeer1.setEmployeer _ worktype ("Development Engineer"); Employeer employeer2 = new Employeer (); employee _ name ("James"); employeer2.setEmployeer _ age (30); employeer2.setEmployeer _ department ("product 2"); employeer2.setEmployeer _ worktype ("Test Engineer "); employeer employeer3 = new Employeer (); employeer3.setEmployeer _ name (""); employeer3.setEmployeer _ age (22); employee _ department ("three products "); worker _ worktype ("data analyst"); Employeer employeer4 = new Employeer (); employeer4.setEmployeer _ name (""); employeer4.setEmployeer _ age (22 ); economic _ department ("Financial department"); Economic _ worktype ("financial personnel"); // insert addEmployeer (employeer1); addEmployeer (employeer2); addEmployeer (employeer3 ); addEmployeer (employeer4); findEmployeerById (26); deleteEmployeer (27); // change employeer2.setEmployeer _ id (28); employee _ age (21 ); employeer2.setEmployeer _ department ("Product 4"); updateEmployeer (employeer2 );}}
Test results:
4 data records inserted, with the ID 25 ~ 28
Then it is deleted on the 27 th.
Modified on 29th
Download the sample project in this article for free
Original works of Lin bingwen Evankaka. Reprinted please indicate the source http://blog.csdn.net/evankaka