Today, I started to learn about MyBatis and read some simple demos on the Internet. The official Chinese guide is also provided .. You can go down ..
Then I wrote a simple one myself ..
First, create a database named mybatis in mysql and create a user table in the database with two field IDs.
The following is the directory structure.
Configuration. 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 alias = "User" type = "User"/>
</TypeAliases>
<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/mybatis"/>
<Property name = "username" value = "root"/>
<Property name = "password" value = "55"/>
</DataSource>
</Environment>
</Environments>
<Mappers>
<Mapper resource = "User. xml"/>
</Mappers>
</Configuration>
User. xml
Public class User {
Private int id;
Private String name;
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;
}
@ Override
Public String toString (){
Return "User [id =" + id + ", name =" + name + "]";
}
}
Test. java
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;
Public class Test {
Public static void main (String [] args) throws IOException {
String resource = "Configuration. xml ";
Reader reader = Resources. getResourceAsReader (resource );
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder (). build (reader );
SqlSession session = sqlMapper. openSession ();
Try {
User user = (User) session. selectOne ("User. selectUser", 2 );
System. out. println ("user name:" + user. getName ());
} Catch (Exception e ){
E. printStackTrace ();
} Finally {
Session. close ();
}
}
}