ssm数据库mysql 增删改查
时间: 2023-07-01 14:18:50 浏览: 105
SSM-数据库Mysql增删改查
好的,下面是使用 SSM 框架进行 MySQL 数据库的增删改查操作的示例代码:
1. 首先在 pom.xml 中添加 MySQL 连接驱动的依赖:
```
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
```
2. 在 Spring 配置文件中配置数据源和 MyBatis:
```
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC" />
<property name="username" value="root" />
<property name="password" value="123456" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:mapper/*.xml" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper" />
</bean>
```
3. 创建实体类和对应的 Mapper 接口:
```
public class User {
private Integer id;
private String name;
private Integer age;
// getter 和 setter 略
}
public interface UserMapper {
void insert(User user);
void update(User user);
void delete(Integer id);
User select(Integer id);
List<User> selectAll();
}
```
4. 创建对应的 Mapper XML 文件:
```
<mapper namespace="com.example.mapper.UserMapper">
<insert id="insert" parameterType="com.example.entity.User">
INSERT INTO user(name, age) VALUES(#{name}, #{age})
</insert>
<update id="update" parameterType="com.example.entity.User">
UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}
</update>
<delete id="delete" parameterType="java.lang.Integer">
DELETE FROM user WHERE id = #{id}
</delete>
<select id="select" parameterType="java.lang.Integer" resultType="com.example.entity.User">
SELECT id, name, age FROM user WHERE id = #{id}
</select>
<select id="selectAll" resultType="com.example.entity.User">
SELECT id, name, age FROM user
</select>
</mapper>
```
5. 在 Service 层中调用 Mapper 接口进行 CRUD 操作:
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public void addUser(User user) {
userMapper.insert(user);
}
@Override
public void updateUser(User user) {
userMapper.update(user);
}
@Override
public void deleteUser(Integer id) {
userMapper.delete(id);
}
@Override
public User getUser(Integer id) {
return userMapper.select(id);
}
@Override
public List<User> getAllUsers() {
return userMapper.selectAll();
}
}
```
以上就是使用 SSM 框架进行 MySQL 数据库的增删改查操作的示例代码,希望能对你有所帮助。
阅读全文