第一个MyBatis程序
功能:将一个学生信息写入到DB
1)导入Jar包
* MyBatis的Jar包
* MySql驱动Jar包
2)定义一个Student类
id,name,age,score
* 主键id要定义为包装类型,不要定义为基本数据类型,例如,不要定义为int,而要定义为Integer
* 若显式地给出了带参构造器,则要显式地给出无参构造器。
– 若当前实体类有可能作父类,那么要创建子类对象时,JVM会调用其父类的无参构造器。
– 若使用了Spring框架,那么要求由Spring容器所管理的类,必须要有无参构造器。
3)创建DB表
表名:student
字段:id,name,age,score
4) 定义Dao接口IStudentDao
public interface IStudentDao {
void insertStudent(Student student);
}
5)定义映射文件
在导入的mybatis.jar包的build path之后,在Referenced Libraries中的mybatis.Jar中有一个xml文件。
里面有两个dtd约束,其中,config.dtd是主配置文件的约束,mapper.dtd是映射文件的约束。
* 是一个XML文件,文件名随意,我们这里叫mapper.xml。
* 该文件定义到Dao接口所在包。
* 约束文件为mybatis-3.4.2.jar ! /org/apache/ibatis/builder/xml/mybatis-3-mapper.dtd
<?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">
<mapper>
<insert id="insertStu" parameterType="com.abc.beans.Student">
insert into student(name,age,score) values(#{name}, #{age}, #{score})
</insert>
</mapper>
如果写上mapper没有提示,用eclipse加上本地dtd文件地址。
6)定义主配置文件
* 是一个XML文件,文件名随意,我们这里叫mybatis.xml
* 定义在src根下
* 约束文件为mybatis-3.4.2.jar ! /org/apache/ibatis/builder/xml/mybatis-3-config.dtd
*
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置运行环境 -->
<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:///test" />
<property name="username" value="root" />
<property name="password" value="123" />
</dataSource>
</environment>
</environments>
<!-- 注册映射文件 -->
<mappers>
<mapper resource="com/abc/dao/mapper.xml" />
</mappers>
</configuration>
7)StudentDaoImpl类继承IStudentDao
package com.abc.dao;
import java.io.IOException;
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.abc.beans.Student;
public class StudentDaoImpl implements IStudentDao {
@Override
public void insertStudent(Student student) {
SqlSession session = null;
try {
// 1. 创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
// 2. 加载主配置文件
InputStream is = Resources.getResourceAsStream("mybatis.xml");
// 3. 创建SqlSessionFactory
SqlSessionFactory factory = builder.build(is);
// 4. 创建SqlSession对象
session = factory.openSession();
// 5. 执行命令
session.insert("insertStu", student);
// 6. SqlSession的提交
session.commit();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 7. SqlSession的关闭
if (session != null) {
session.close();
}
}
}
}
8)主方法测试
package com.abc.test;
import com.abc.beans.Student;
import com.abc.dao.IStudentDao;
import com.abc.dao.StudentDaoImpl;
public class MyTest {
public static void main(String[] args) {
Student student = new Student("张三", 12, 23.5);
IStudentDao dao = new StudentDaoImpl();
dao.insertStudent(student);
}
}
9)日志log4j.properties
##define an appender named console
log4j.appender.console=org.apache.log4j.ConsoleAppender
#The Target value is System.out or System.err
log4j.appender.console.Target=System.out
#set the layout type of the apperder
log4j.appender.console.layout=org.apache.log4j.PatternLayout
#set the layout format pattern
log4j.appender.console.layout.ConversionPattern=[%-5p] %m%n
##define a logger
#log4j.rootLogger=debug,console
log4j.logger.xxx=debug,console
遇到的问题:
log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig
for more info.
[DEBUG] ==> Preparing: inesert into student(name,age,score) value(?,?,?)
[DEBUG] ==> Parameters: 张三(String), 12(Integer), 23.5(Double)
Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException:
### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'inesert into student(name,age,score) value('å¼ ä¸‰',12,23.5)' at line 1
### The error may involve xxx.insertStu-Inline
### The error occurred while setting parameters
### SQL: inesert into student(name,age,score) value(?,?,?)
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'inesert into student(name,age,score) value('å¼ ä¸‰',12,23.5)' at line 1
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:200)
at org.apache.ibatis.session.defaults.DefaultSqlSession.insert(DefaultSqlSession.java:185)
at com.abc.dao.StudentDaoImpl.insertStudent(StudentDaoImpl.java:29)
at com.abc.test.MyTest.main(MyTest.java:15)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'inesert into student(name,age,score) value('å¼ ä¸‰',12,23.5)' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3515)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3447)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1951)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2101)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2554)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1761)
at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1021)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.ibatis.logging.jdbc.PreparedStatementLogger.invoke(PreparedStatementLogger.java:59)
at com.sun.proxy.$Proxy1.execute(Unknown Source)
at org.apache.ibatis.executor.statement.PreparedStatementHandler.update(PreparedStatementHandler.java:46)
at org.apache.ibatis.executor.statement.RoutingStatementHandler.update(RoutingStatementHandler.java:74)
at org.apache.ibatis.executor.SimpleExecutor.doUpdate(SimpleExecutor.java:50)
at org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:117)
at org.apache.ibatis.executor.CachingExecutor.update(CachingExecutor.java:76)
at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:198)
... 3 more
1、先看项目中右键->properties->java build path中是否有jar包丢失,有的jar包是不是不存在。
2、代码错误,配置文件中的insert代码敲成inesrt。错误找了好久。