Sure,下面是MyBatis实现注册及获取Mapper的完整攻略:
REGISTRATION
Resources Configuration
在MyBatis中注册Mapper的第一步是添加资源配置,也就是MyBatis的XML配置文件。MyBatis通过解析这些配置文件来构建SqlSession工厂,进而创建SqlSession实例。我们需要创建以下两个配置文件。
mybatis-config.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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:XE" />
<property name="username" value="id" />
<property name="password" value="password" />
</dataSource>
</environment>
</environments>
<!-- 注册mapper -->
<mappers>
<mapper resource="com/example/UserMapper.xml" />
<mapper class="com.example.UserMapper" />
</mappers>
</configuration>
在这个XML配置文件中,我们指定了:
- 数据库连接信息(driver, url, username, password)。
- 一个名为“development”的环境。(每个环境都拥有自己的事务管理器和数据源。)
- 我们要注册的mappers(可以通过文件或类两种方式进行注册)。
Mapper interface
创建一个Java Mapper接口,用于定义需要执行的SQL语句:
package com.example;
import java.util.List;
public interface UserMapper {
User getUserById(int id);
List<User> getAllUsers();
void insertUser(User user);
void deleteUser(int id);
}
Implementing Mapper
创建基于XML或注解的Mapper实现,以便让MyBatis知道我们如何实现Java Mapper接口中定义的SQL操作。
XML Based Implementations
为了实现基于XML的mappers,我们需要创建一个XML文件来定义mapper的SQL语句。XML文件的名字必须与Java Mapper接口相同,并放在同一目录下。
比如,对于上面创建的UserMapper接口,我们应该创建一个名为UserMapper.xml的XML文件。
<?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 namespace="com.example.UserMapper">
<resultMap id="userMap" type="User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
</resultMap>
<select id="getUserById" resultMap="userMap">
SELECT * FROM users WHERE id=#{id}
</select>
<select id="getAllUsers" resultMap="userMap">
SELECT * FROM users
</select>
<insert id="insertUser" parameterType="User">
INSERT INTO users(username, password) VALUES(#{username}, #{password})
</insert>
<delete id="deleteUser">
DELETE FROM users WHERE id=#{id}
</delete>
</mapper>
在这个XML文件中,我们定义了ResultMaps,我们的Java Mapper接口中方法对应的SQL语句和参数类型。
Annotation Based Implementations
基于注解的mappers需要在Java Mapper接口中添加@Mapper注解,并在实现类中添加@Select,@Insert,@Update和@Delete等具有相应注解的SQL语句。
比如,我们的Java Mapper接口和实现类可以这样:
package com.example;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users WHERE id=#{id}")
User getUserById(int id);
@Select("SELECT * FROM users")
List<User> getAllUsers();
@Insert("INSERT INTO users(username, password) VALUES(#{username}, #{password})")
void insertUser(User user);
@Delete("DELETE FROM users WHERE id=#{id}")
void deleteUser(int id);
}
Building SqlSessionFactory
使用以上实现后,我们需要创建SqlSessionFactory实例:
package com.example;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MyBatisUtil {
private static SqlSessionFactory sqlSessionFactory;
private static final String RESOURCE_NAME = "mybatis-config.xml";
static {
try {
InputStream inputStream = Resources.getResourceAsStream(RESOURCE_NAME);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
System.err.println("Failed to read resource file '" + RESOURCE_NAME + "'.");
e.printStackTrace();
}
}
public SqlSession getSqlSession() {
return sqlSessionFactory.openSession(true);
}
}
这样就可以创建SqlSessionFactory并调用它的openSession()方法来获取SqlSession了。
GETTING MAPPERS
有了SqlSession和Java Mapper接口,我们可以使用以下方法获取Mapper:
From SqlSession
// 获取SqlSession
SqlSession sqlSession = new MyBatisUtil().getSqlSession();
// 获取Mapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Automatically from Spring
对于使用Spring框架的应用程序,可以轻松自动创建Mapper Bean:
<!-- 在.springBootConfiguration类中增加@MapperScan注解-->
@MapperScan("com.example")
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
// 或
@Configuration
public class MyBatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/*.xml"));
return sessionFactory.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
@Bean
public DataSource dataSource() {
return new DriverManagerDataSource("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull",
"username", "password");
}
}
使用过程中必须将MyBatis Maven依赖项加入到您的项目中,并使用在您的项目中调用上述方法的代码块,以使SQL语句与数据库进行沟通。
示例1将说明如何使用MyBatis建立并访问一个简单的数据库:
示例1:
public class Example1 {
public static void main(String[] args) {
SqlSession session = new MyBatisUtil().getSqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = new User(1, "bob");
mapper.insertUser(user);
List<User> users = mapper.getAllUsers();
users.forEach(System.out::println);
}
}
示例2将说明如何使用MyBatis配置插件(如分页插件):
示例2:
public class Example2 {
public static void main(String[] args) {
SqlSession session = new MyBatisUtil().getSqlSession();
com.github.pagehelper.PageHelper.startPage(1, 3);
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> users = mapper.getAllUsers();
PageInfo<User> pageInfo = new PageInfo<>(users);
System.out.println(pageInfo);
}
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:MyBatis实现注册及获取Mapper - Python技术站