MVC模板
MVC模板
mybatis-config
<?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>
<settting>
<setting value="LOG4J" name="logImpl"/>
</settting>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<dataSource type="UNPOOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/demo"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="my.mapper.UserMapper"/>
</mappers>
</configuration>
InitSession类
package my.tool;
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;
public class InitSession {
private static SqlSessionFactory factory;
static {
InputStream in;
try {
in = Resources.getResourceAsStream("mybatis-config.xml");
factory = new SqlSessionFactoryBuilder().build(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static SqlSession getSession() {
return factory.openSession();
}
}
生成mapper对象的方法
业务类功能需要对数据库进行操作,需要用到mapper接口链接数据库
//定义SqlSession对象
SqlSession session = InitSession.getSession();
//定义Mapper对象
UserMapper mapper = session.getMapper(UserMapper.class);
注:这两条可以使用全局变量
JSP实现连接数据库(利用JSTL)
<sql:setDataSource driver="com.mysql.jdbc.Driver "
url="jdbc:mysql://43.143.152.156:3060/usermanager"
user="root"
password="Zhuwenxue2002"
var="snapshot"
/>
<sql:query var="result"
sql="SELECT password from user WHERE ${username};"
dataSource="${snapshot}"
/>