Ibatis--An example of student information management

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/l1028386804/article/details/47107647
IBatis Introduction:

IBatis is an open source project for Apache, an O/R Mapping solution, IBatis is the biggest feature is the small, quick to get started. If you don't need too many complex features, IBatis is the simplest solution to meet your requirements and be flexible enough, and now IBatis has been renamed MyBatis.

Official website:http://www.mybatis.org/

Build Ibatis development environment:

1, import the relevant jar package, Ibatis-2.3.0.677.jar, Mysql-connector-java-5.1.6-bin.jar

2. Write the configuration file:

The properties file for the JDBC connection

General configuration file, Sqlmapconfig.xml

About each entity's mapping file (map file)

Student.java:

Package Com.lyz.entity;import java.sql.date;/** * Student entity class * @author Liuyazhuang * */public class Student {//Note there is a need to ensure that there is a non-parametric method, because the mappings, including Hibernate, are all using reflection,//If no parameterless constructs may occur the problem private int id;private String name;private Date birth;private float score;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public Date Getbirth () {return birth;} public void Setbirth (Date birth) {This.birth = birth;} public float Getscore () {return score;} public void SetScore (float score) {this.score = score;} @Overridepublic String toString () {return "Student [id=" + ID + ", name=" + name + ", birth=" + birth+ ", score=" + Score + "]";} }
sqlmap.properties
Driver=com.mysql.jdbc.driverurl=jdbc:mysql://localhost:3307/ibatisusername=rootpassword=root
Student.xml

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE sqlmap Public "-//ibatis.apache.org//dtd SQL Map 2.0//en" "Http://ibatis.apache.org/dtd/sql-map-2.dtd" > <sqlMap><!--by Typealias allows us to use the Student entity class below without having to write the package name--><typealias alias = "Student" type= " Com.lyz.entity.Student "/><!--then changed SQL, you do not need to change the Java code--><!--ID represents the SQL statement in Select, ResultClass indicates the type of the returned result- -><select id = "Selectallstudent" resultclass= "Student" >select * fromtbl_student</select><!-- Parameterclass indicates that the contents of the parameter--><!--#表示这是一个外部调用的需要传进的参数, which can be understood as placeholder--><select id = "Selectstudentbyid" parameterclass= "int" resultclass= "Student" >select * from Tbl_student where id= #id #</select><!-- Note the ResultClass type here, using the student type depends on queryForList or queryforobject--><select id = "Selectstudentbyname" parameterclass= "String" resultclass= "Student" >select Name,birth,score from tbl_student where name like '% $name $% ' </select><insert id = "Addstudent" parameterclass= "StudenT ">insert intotbl_student (Name,birth,score) VALUES (#name #, #birth #, #score #) <selectkey resultclass =" int " keyproperty= "id" >select @ @identity as inserted<!--There is a need to explain the different database primary key generation, different ways for the respective database:--><!--MySQL: SELECT last_insert_id () as value--><!--mssql:select @ @IDENTITY as value--><!--oracle:select Stockidsequen Ce. Nextval as VALUE from DUAL--><!--It is also important to note that different database manufacturers generate primary keys differently, and some are pre-generated (pre-generate) primary keys, such as Oracle and PostgreSQL. Some are post-generation (post-generate) primary keys, such as MySQL and SQL Server, so if you are an Oracle database, you need to write Selectkey before insert--></selectkey></ Insert><delete id = "Deletestudentbyid" parameterclass= "int" ><!--#id # ID can be arbitrarily taken, but the above insert will have an effect, Because the name above will look up from the attributes in the student to find the--><!--we can also understand that if there is a # placeholder, then Ibatis will call the property in Parameterclass to assign the value-->delete from Tbl_ Student where id= #id #</delete><update id = "Updatestudent" parameterclass= "student" >update tbl_student set Name= #name #,birth= #birth #,score= #score # where id= #id #</update></sqlmap> 
Sqlmapconfig.xml

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE sqlmapconfig Public "-//ibatis.apache.org//dtd SQL Map Config 2.0//en" "http://ibatis.apache.org/dtd/ Sql-map-config-2.dtd "><sqlMapConfig><!--configuration file referencing the JDBC property--><properties resource=" Sqlmap.properties "/><!--using JDBC for transaction management--><transactionmanager type=" JDBC "><!--data source-->< DataSource type= "Simple" ><property name= "JDBC. Driver "value=" ${driver} "/><property name=" JDBC. Connectionurl "value=" ${url} "/><property name=" JDBC. Username "value=" ${username} "/><property name=" JDBC. Password "value=" ${password} "/></datasource></transactionmanager><!--can write a mapping file for multiple entities-->< Sqlmap resource= "Com/lyz/entity/student.xml"/></sqlmapconfig>
Studentdao
Package Com.lyz.dao;import java.util.list;import com.lyz.entity.student;/** * Student Data Manipulation interface * This class encapsulates the student class of additions and deletions to the operation * @author Liuyazhuang * */public interface Studentdao {/*** Add student information * * @param student* Student Entity * @return returns whether to add Success */public Boolean addstude NT (Student Student)/*** Delete Student information based on student ID * * @param id* student id* @return Delete succeeded */public boolean deletestudentbyid (int id);/*** update Student Information * * @param student* Student entity * @return Update is successful */public Boolean updatestudent (student student);/*** query all student information * * @return back to Student list */public list<student> selectallstudent ();/*** student information based on student's name * * @param name* student name * @return Student Information List */public <Student> selectstudentbyname (String name)/*** query student information based on student ID * * @param id* student id* @return Student Object */public Student Selectstudentbyid (int id); }
Studentdaoimpl
Package Com.lyz.dao.impl;import Java.io.ioexception;import Java.io.reader;import java.sql.sqlexception;import Java.util.list;import Com.ibatis.common.resources.resources;import Com.ibatis.sqlmap.client.sqlmapclient;import Com.ibatis.sqlmap.client.sqlmapclientbuilder;import Com.lyz.dao.studentdao;import com.lyz.entity.Student;/** * The implementation class of the student data operation interface * * @author Liuyazhuang * */public class Studentdaoimpl implements Studentdao {//Sqlmapclient client Object private s Tatic sqlmapclient sqlmapclient = null;//Read the configuration file in a static code block static {try {reader reader = Resources.getresourceasreader (" Sqlmapconfig.xml "); sqlmapclient = sqlmapclientbuilder.buildsqlmapclient (reader); Reader.close ();} catch (IOException e) {e.printstacktrace ();}} @Overridepublic boolean addstudent (Student Student) {Object object = Null;boolean flag = False;try {object = sqlmapclient. Insert ("Addstudent", student); System.out.println ("Add return value for student information:" + object);} catch (SQLException e) {e.printstacktrace ();} if (Object! = null) {flag = true;} return flag;} @Overridepublic boolean Deletestudentbyid (int id) {Boolean flag = False;object Object = Null;try {object = Sqlmapclient.d Elete ("Deletestudentbyid", id); System.out.println ("Delete Student information return value:" + Object + ", where the number of rows affected is returned");} catch (SQLException e) {e.printstacktrace ();} if (Object! = null) {flag = true;} return flag;} @Overridepublic boolean updatestudent (Student Student) {Boolean flag = False;object Object = Null;try {object = Sqlmapclie Nt.update ("Updatestudent", student); SYSTEM.OUT.PRINTLN ("Update the return value of student information:" + Object + ", returns the number of rows affected");} catch (SQLException e) {e.printstacktrace ();} if (Object! = null) {flag = true;} return flag;} @Overridepublic list<student> selectallstudent () {list<student> students = null;try {students = Sqlmapclient.queryforlist ("Selectallstudent");} catch (SQLException e) {e.printstacktrace ();} return students;} @Overridepublic list<student> selectstudentbyname (String name) {list<student> students = null;try { Students = Sqlmapclient.queryforlist ("SelectstudentbynamE ", name);} catch (SQLException e) {e.printstacktrace ();} return students;} @Overridepublic Student Selectstudentbyid (int id) {Student Student = null;try {Student = (Student) Sqlmapclient.queryforo Bject ("Selectstudentbyid", id);} catch (SQLException e) {e.printstacktrace ();} return student;}}
Testibatis.java

Package Com.lyz.test;import Java.sql.date;import Java.util.list;import com.lyz.dao.studentdao;import Com.lyz.dao.impl.studentdaoimpl;import com.lyz.entity.student;/** * Ibatis Framework Test class * @author Liuyazhuang * */public class Testibatis {public static void main (string[] args) {Studentdao Studentdaoimpl = new Studentdaoimpl (); SYSTEM.OUT.PRINTLN ("test Insert"); Student addstudent = new Student () Addstudent.setname ("John Doe"); Addstudent.setbirth (date.valueof ("1992-09-02")); Addstudent.setscore (88); System.out.println (Studentdaoimpl.addstudent (addstudent)); SYSTEM.OUT.PRINTLN ("Test based on ID query"); System.out.println (Studentdaoimpl.selectstudentbyid (1)); SYSTEM.OUT.PRINTLN ("Test fuzzy query"); list<student> mohulists = studentdaoimpl.selectstudentbyname ("Li"); for (Student student:mohulists) { SYSTEM.OUT.PRINTLN (student);} SYSTEM.OUT.PRINTLN ("Test query All"); list<student> students = Studentdaoimpl.selectallstudent (); for (Student student:students) {System.out.println ( Student);} SYSTEM.OUT.PRINTLN ("Test update student Information"); Student updatestudent = new Student (); Updatestudent.setid (1); Updatestudent.setname ("Lee 41"); Updatestudent.setbirth (Date.valueof (" 2011-08-07 ")); Updatestudent.setscore (21); System.out.println (Studentdaoimpl.updatestudent (updatestudent)); System.out.println ("Delete student information by id"); System.out.println (Studentdaoimpl.deletestudentbyid (1));}}

Run effect


Note: I modified my own database default port, so my port is 3307,mysql default port is 3306, if you do not change the port, the port is 3306.

Warm tip: You can go to the link http://download.csdn.net/detail/l1028386804/8940401 download the complete Ibatis implementation of the Student Information management sample source code.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Ibatis--An example of student information management

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.