ubuntu20.04中mybatis连接mysql
时间: 2024-01-14 20:43:53 浏览: 108
可以使用以下步骤配置:
1. 安装MySQL和MyBatis
```
sudo apt install mysql-server mysql-client
sudo apt install libmysql-java
sudo apt install maven
```
2. 创建数据库和表
```
mysql -u root -p
CREATE DATABASE testdb;
USE testdb;
CREATE TABLE user (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
age INT NOT NULL,
email VARCHAR(50) NOT NULL
)
```
3. 配置MyBatis
在mybatis-config.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/testdb?useSSL=false&serverTimezone=UTC" />
<property name="username" value="root" />
<property name="password" value="yourpassword" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml" />
</mappers>
</configuration>
```
4. 编写Mapper接口和SQL语句
创建UserMapper.xml文件,添加以下内容:
```
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectAllUsers" resultType="User">
SELECT * FROM user
</select>
</mapper>
```
创建User.java类和UserMapper.java接口
```
public class User {
private int id;
private String name;
private int age;
private String email;
// getters and setters
}
public interface UserMapper {
List<User> selectAllUsers();
}
```
5. 测试MyBatis连接MySQL
在代码中使用UserMapper接口中的方法查询数据
```
public static void main(String[] args) {
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
try(SqlSession session = sessionFactory.openSession()) {
UserMapper userMapper = session.getMapper(UserMapper.class);
List<User> users = userMapper.selectAllUsers();
for(User user : users) {
System.out.println(user.getName());
}
}
}
```
阅读全文