A simple case of Mybatis
keep_foolish
- java
- Apache
- The database
- The console
- string
- xml
- session
- ibatis
- mybatis
Abstract: Create a simple Mybatis case case function to write a Java program through Mybatis connect to MySQL database and insert a record. Step 1. Create a Java project mybatistest 2. Introduce the JAR package log4J-1.
Create a simple mybatis case:
Case function:
Write a Java program through mybatis connect to MySQL database and insert a record.
Project steps:
1. Create a New Java project mybatistest
2. Import jar package:
- Log4j – 1.2.17. Jar
- Mybatis – 3.4.6. Jar
- Mysql connector – Java – 5.1.29. Jar
3. Create two packages under SRC:
- com.radish.domain
- com.radish.mapper
- test
4. Create table:
CREATE TABLE `tb_user` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(18) DEFAULT NULL,
`SEX` char(2) DEFAULT NULL,
`AGE` int(11) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;Copy the code
5. Create a POJO SRC/com/radish/domain/User. Java:
private Integer id;
private String name;
private String sex;
private Integer age;Copy the code
Omit the constructor and get/set methods
6. Create mybatis – config. XML
See my other post for more details
Create log4j.properties:
log4j.rootLogger=ERROR, stdout
log4j.logger.com.radish.mapper.UserMapper=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%nCopy the code
8. Create test class:
package Test; import java.io.InputStream; 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.radish.domain.User; Public class MybatisTest {public static void main(String[] args) throws Exception{// Read the configuration of mybatis-config.xml InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); // Initialize mybatis, SqlSessionFactory SqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); / / create a session object SqlSession session. = sqlSessionFactory openSession (); User User = new User("admin", "male ", 26); session.insert("com.radish.mapper.UserMapper.save", user); session.commit(); session.close(); }}Copy the code
Execution Result:
The console outputs log information
Database:
mybatist… [keep_foolish].1520834883.zip
Use the cloud habitat community APP, comfortable ~
For details, please click
- To: