1. 程式人生 > 其它 >java——mybatis——Mybatis註解開發——@Update——修改資料

java——mybatis——Mybatis註解開發——@Update——修改資料

DAO介面:

package com.sunxl.dao;

import com.sunxl.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface UserDao {

    @Select(
"select * from users") List<User> findAll(); @Insert("insert into users (name,age) values(#{name},#{age})") @SelectKey(statement = "select last_insert_id()", keyProperty = "id", keyColumn = "id", resultType = int.class ,before = false) int saveUser(User user); @Update("update users set name = #{name},age = #{age} where id = #{id}")
int updateUser(User user); // // int deleteUser(Integer id); // // User findById(Integer id); // // List<User> findByName(String name); // // int findTotal(); // // int saveInsertUser(User user); }

測試執行:

import com.sunxl.dao.UserDao;
import com.sunxl.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; import java.util.List; public class MybatisTest { public static void main(String[] args) throws IOException { // InputStream config = Resources.getResourceAsStream("mybatis-config.xml"); // // SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); // SqlSessionFactory factory = builder.build(config); // SqlSession ss = factory.openSession(); // UserDao userdao = ss.getMapper(UserDao.class); // // // List<User> users = userdao.findAll(); // // for (User user: users){ // System.out.println(user); // } // // // ss.commit(); // ss.close(); // config.close(); InputStream config = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(config); SqlSession ss = factory.openSession(); UserDao userdao = ss.getMapper(UserDao.class); User as = new User(); as.setName("mei_guo"); as.setAge(1005); as.setId(1005); int a = userdao.updateUser(as); System.out.println(a); System.out.println(as.toString()); ss.commit(); ss.close(); config.close(); } }