mybatis example
时间: 2023-08-27 20:22:47 浏览: 76
mybatis例子
Sure! Here's a simple example of using MyBatis:
First, you need to set up your database connection and create a configuration file for MyBatis. In this example, let's assume you have a table called "users" with columns "id" and "name".
1. Create a configuration file named "mybatis-config.xml" with the following content:
```xml
<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://localhost:3306/mydatabase"/>
<property name="username" value="your_username"/>
<property name="password" value="your_password"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
```
2. Create a Java class called "User" representing the users table:
```java
public class User {
private int id;
private String name;
// Getters and setters
}
```
3. Create a mapper XML file named "UserMapper.xml" with the following content:
```xml
<mapper namespace="com.example.UserMapper">
<resultMap id="userResultMap" type="User">
<id property="id" column="id"/>
<result property="name" column="name"/>
</resultMap>
<select id="getUserById" resultMap="userResultMap">
SELECT id, name FROM users WHERE id = #{id}
</select>
<insert id="insertUser" parameterType="User">
INSERT INTO users (name) VALUES (#{name})
</insert>
</mapper>
```
4. Create an interface called "UserMapper" with the following content:
```java
public interface UserMapper {
User getUserById(int id);
void insertUser(User user);
}
```
5. Finally, you can use MyBatis in your Java code:
```java
public class Main {
public static void main(String[] args) {
// Create a SqlSessionFactory
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// Create a SqlSession
try (SqlSession session = sqlSessionFactory.openSession()) {
// Get the UserMapper instance
UserMapper userMapper = session.getMapper(UserMapper.class);
// Get a user by ID
User user = userMapper.getUserById(1);
System.out.println(user.getName());
//
阅读全文