"MyBatis" Helloworld

Source: Internet
Author: User
Tags mysql download

MyBatis, like Hibernate, is a nosql tool, and what is NoSQL. Originally, should write SQL statements in Java, in order to MySQL and other databases, but after the NoSQL tool, in Java you only need a class method to the database can be added to the search, of course, the original SQL statement or to write, Just like MyBatis and hibernate these nosql tools separate the SQL statements from the Java code.


And whether this tool is good or not, and even personal feeling a little bit of trouble, however, now the enterprise is good, the industry's Java EE Company, like to use this framework, so you basically have to be.

First, MyBatis download, configuration

MyBatis and Web pages actually have nothing to do with it, it's just a matter of handling Java and the exchange between databases. So, using a Java project, not the dynamic Web project in Eclipse, illustrates this problem.

The project structure of the final MyBatis HelloWorld is posted first.


You first need two jars, one is connected to MySQL must be a jar, here, as a MySQL example, Orcale and other databases are replaced by the corresponding jar package can be to the official website of MySQL download: https://dev.mysql.com/downloads/ connector/j/, after downloading the Mysql-connector-java-5.1.44-bin.jar to your engineering directory, general in the engineering directory to create a new lib, put these bags.


Then download the mybatis,http://www.softpedia.com/get/programming/other-programming-files/mybatis.shtml, also take the core jar inside, and put it under the Lib of your engineering directory.


Then set up your Java project in eclipse to load these lib,mybatis configuration is officially completed.


Second, the HelloWorld of MyBatis

The goal is to have the following this has been lifted countless times a chestnut waste table user data:


Print it out in the Java console, of course, and you'll print it, and organize the data into spring MVC or strust2 that's what it means.


1, first, first in the SRC directory under the new 3 package test.dao,test.entity,test.mapper,src is the meaning of the source code.


Then under Test.entity, create the following user.java:

Package test.entity;

public class User {
	
	private Integer ID;
	Private String username;
	private String password;

	Public Integer GetId () {return
		ID;
	}

	public void SetId (Integer id) {
		this.id = ID;
	}

	Public String GetUserName () {return
		username;
	}

	public void Setusername (String username) {
		this.username = username;
	}

	Public String GetPassword () {return
		password;
	}

	public void SetPassword (String password) {
		this.password = password;
	}
 
}

The long, boring getter and setter can completely write 3 variables private Integer id;private string username;private string password, using alt+shift+ s lets eclipse generate itself, here in the Java three variables corresponding to the database MySQL inside the three fields.


2, after completing the MyBatis configuration in the root directory configuration.xml, this file contains the entire MyBatis information, later need to mybatis communicate the other tables of the database and Java engineering links, in this XML file to add a fake example add a child.

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-co Nfig.dtd "> <configuration> <typeAliases> <typealias type=" Test.entity.User "alias=" User "/>< !--indicates that there is an entity user, and that the Java file for the profile is the user--> </typeAliases> <!--under Test.entity to specify the connection information about MySQL--> < 
			Environments default= "Development" > <environment id= "Development" > <transactionmanager type= "jdbc"/> <datasource type= "Pooled" > <property name= "Driver" value= "Com.mysql.jdbc.Driver"/> <property N Ame= "url" value= "jdbc:mysql://localhost:3306/test"/> <property name= "username" value= "root"/> <prope Rty name= "Password" value= "root"/> </dataSource> </environment> </environments> &LT;MAPPERS&G
		T <mapper resource= "Test/mapper/user.xml"/><!--indicate the commonly used SQL methods contained in the User's table, Test/mapper/user.xmlis an XML file that indicates the connection between Java methods and SQL syntax--> </mappers> </configuration>      

3, then under the Test.mapper package to create a new User.xml, this file indicates the SQL statement and Java method of the corresponding relationship

<?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" >
<!--indicate the FindByID method under Userdao.java under the SQL corresponding Test.dao for SELECT * from user where Id=#{id}-->
<!-- At the same time, the return of FindByID is a class of user type-->
<mapper namespace= "Test.dao.UserDao" > <select id= "
	FindByID" Parametertype= "HashMap" resulttype= "user" >
		select * from User where id=#{id}
	</select>

4, and then under the Test.dao a new Userdao.java, this file to write an interface on the line.

Package Test.dao;

Import Test.entity.User;

Public interface Userdao {public
	User FindByID (Integer ID);
}

Through the above four steps, MyBatis configuration is complete, the SRC root directory to create a new Mybatishelloworld.java can see the final effect of

Import java.io.IOException;
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 Test.dao.UserDao;

Import Test.entity.User; public class Mybatishelloworld {/* MyBatis connection to the database, the future can be written by spring in XML let the project come up with this code, directly complete injection/private static SQLSESSIONFAC
		Tory getsessionfactory () {sqlsessionfactory sessionfactory = null;
		String resource = "Configuration.xml";
		try {sessionfactory = new Sqlsessionfactorybuilder (). Build (resources. Getresourceasreader (Resource));
		catch (IOException e) {e.printstacktrace ();
	return sessionfactory; public static void Main (string[] args) {sqlsession sqlsession = Getsessionfactory (). Opensession ();//Connect Database Userda o Userdao = Sqlsession.getmapper (Userdao.class);//NoSQL directly get a userdao user user = Userdao.findbyid (1);//direct access to Getter SE Tter reads and writes the data inside the database System.out.println ("The ID is 1 username=" + User.getusername ());
	System.out.println ("Password= with ID 1" + user.getpassword ());
 }

}


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.