MyBatis Build Environment _mybatis Environment

Source: Internet
Author: User
Tags log4j

First, import the jar package

JUnit One, MySQL one, mybatis core jar One, MyBatis relies on JAR9


Then you create the entity classes, and the test class


In entity class User.jsva

Package Com.hpe.po;

Import Java.util.Date;
	public class User {private int id;
	Private String username;
	Private Date birthday;
	Private String sex;
	
	Private String address;
	Public User () {super ();
		public User (int ID, string username, Date birthday, String sex, string address) {super ();
		This.id = ID;
		This.username = Username;
		This.birthday = Birthday;
		This.sex = sex;
	this.address = address;
	public int getId () {return id;
	The public void setId (int id) {this.id = ID;
	Public String GetUserName () {return username;
	} public void Setusername (String username) {this.username = username;
	Public Date Getbirthday () {return birthday;
	The public void Setbirthday (Date birthday) {this.birthday = birthday;
	Public String Getsex () {return sex;
	} public void Setsex (String sex) {this.sex = sex;
	Public String getaddress () {return address;
	public void setaddress (String address) {this.address = address; } @OvErride public String toString () {return "User [id= + ID +", username= "+ Username +", birthday= "+ Birthday +", se
	x= "+ Sex +", address= "+ address +"]; }
	

}

Write Core profile Sqlmapconfig.xml

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration> <typeAliases> <!--<typealias type= "Com.hpe.po.User" alias= "User"/> The method is to specify that the user class alias under the package is user, and when using the class mapping file, when describing the parameter or return type, you can use the user--> <!--batch to specify the name of the package, batch create the alias of the class under the package, that is, all the class aliases are created The default is that the alias is the name of the class under the package, and the first letter is case-insensitive. --> <package name= "Com.hpe.po"/> </typeAliases> <environments default= "Development" > <envir Onment id= "Development" > <transactionmanager type= "jdbc" > <!--Transaction management is managed by JDBC--> </transactionma nager> <!--configuration database connection information--> <datasource type= "Pooled" > <!--database connection pool--> <property name= "Driver" value= "Com.mysql.jdbc.Driver"/> <property name= "url" value= "JDBC:MYSQL://LOCALHOST:3306/MYBATISCL Ass?characterencoding=utf-8 "/> <property name=" username "value=" "Root"/> <properTy name= "password" value= "/> <!--Configuration connection information--> </dataSource> </environment> </environmen  Ts> <mappers> <!--the relative path of the Mapper.xml file, this is in the SRC root directory, and if it is under Com.po, add Com.po.UserMapper.xml--> <mapper Resource= "Usermapper.xml"/> <!--MyBatis Framework needs to load the mapping file to add Usermapper.xml to sqlmapconfig.xml>-->  Mappers> </configuration>

Of course, the database configuration can also be separated, written in the Db.properties file, that the core refers to the file needs to be modified, also need to introduce properties file.

Properties File content:

Jdbc.driver=com.mysql.jdbc.driver
jdbc.url=jdbc:mysql://localhost:3306/mybatisclass?characterencoding= Utf-8
jdbc.username=root
jdbc.password=

Driver: Driver name

URL: Database access path

Username: Login database name

Password: Login Database Password

Note: In the properties file, the information after the equals sign is not marked with punctuation, and finally they are stitching together as:

Jdbc:mysql://localhost:3306/mybatisclass?characterencoding=utf-8&username=root&password=pwd

So we're modifying the Sqlmapconfig.xml configuration file

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration> <properties resource= "Db.properties > <!--<property name=" Driver "value=" Com.mysql.jdbc.Driver "/>--> <!--introduce db.properties file, pay attention to the path problem, change the file I was placed in the SRC directory--> </properties> < typealiases> <!--<typealias type= "Com.hpe.po.User" alias= "User"/>--> <!--batch specify alias name to specify Package name, batch Create package class The alias alias is the name of the class under the package, and the first letter is case-insensitive. --> <package name= "Com.hpe.po"/> </typeAliases> <environments default= "Development" > <envir Onment id= "Development" > <transactionmanager type= "JDBC" > </transactionManager> <datasource ty Pe= "Pooled" > <property name= "Driver" value= "${jdbc.driver}"/> <property name= "url" value= "${jdbc.url} "/> <property name= username" value= "${jdbc.username}"/> <property "name="Password "value=" ${jdbc.password} "/> </dataSource> </environment> </environments> <mappers > <!--relative path of mapper.xml file--> <mapper resource= "Usermapper.xml"/> </mappers> </configuration& Gt

Usermapper.xml:

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <!--  SELECT statement--> <select id= "Selectuserbyid" parametertype= "int" resulttype= "Com.hpe.po.User" > select * from User Where Id=#{id} <!--query user--> <!--ids based on IDS: Identifying SQL statements, Statemenid--> <!--parametertype: input parameters, input mapping type
		; <!--resulttype: Map output result type--> <!--#{id}, assign a value to a placeholder if ParameterType is a simple data type, any content in {} If ParameterType is an object data type,
			 
			 The value in {}, the property of the corresponding object, cannot be written casually. #{} mode differs from ${} mode: #{} is a placeholder, ${} is stitching--> </select> <select id= "Selectusernamebyname" parametertype= "Strin" G "Resulttype=" Com.hpe.po.User > select * from User where sex= ' girl ' and username like '%${value}% ' <!--${} Using the stitching method, quite like '% ' +value+% '--> </select> <!--INSERT statement--> <insert id= ' register ' parametertype= ' com. Hpe.po.User "> <!--Order: This sentence executes sequentially resulttype: Execution result map type KEYPRoperty: The query results are mapped to the attribute of the input parameter. --> <!--If the alias <typeAliases> attribute is configured in the Core profile config file, it will be done directly with the alias, such as parametertype= "user"--> <selectkey Order= "after" resulttype= "int" keyproperty= "id" > select last_insert_id () <!--returns the value of the primary key after the increment and places it in the keyproperty= "id" ID--> </selectKey> INSERT INTO user (username, password, sex, realname) VALUES (#{username}, #{password}, #{sex}, #{realname}) <!--INSERT statement--> </insert> <!--DELETE statement--> <delete id= "Delete" Paramet ertype= "int" > <!--delete,update,insert do not have to indicate the return value type, as long as the ParameterType incoming type is described--> the delete from user where id = #
		{ID} </delete> <!--UPDATE statement--> <update id= "Updatebtid" parametertype= "user" > Update user set Username=#{username},sex=#{sex},realname=#{realname} where Id=#{id} </update> </mapper>

Create a log file under src log4j.properties

# Global Logging Configuration
log4j.rootlogger=debug, stdout
# Console output ...
Log4j.appender.stdout=org.apache.log4j.consoleappender
log4j.appender.stdout.layout= Org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.conversionpattern=%5p [%t]-%m%n

Writing test class:

public class Usertest {
	private sqlsessionfactory factory;
	@Before public
	void SetUp () throws ioexception{
		InputStream Inputstream=resources.getresourceasstream (" Sqlmapconfig.xml ");
		Factory =new Sqlsessionfactorybuilder (). Build (InputStream);
	
	@Test is to add annotations for unit tests and
		read configuration files
		using JUnit @Test public void Testselctusrbyname () throws ioexception{// Sqlsession session=factory.opensession ();
		SelectOne Query single
		//statementid--"Namespace+statementid
		//
		System.out.println ();//syso
		List <User> list=session.selectlist ("User.selectusernamebyname", "three");
		SYSTEM.OUT.PRINTLN (list);
		Session.commit (): The database does not change the session.close () if the transaction is committed when adding or deleting the change
		;

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.