作业需求:
用户登录
User表中数据:
在控制台中输入:
程序运行最终结果:在控制台打印
1.按照数据表的数据用sql建表(表名User)
2.使用sql插入数据
将数据表中的数据封装成JavaBean(类名为User)
参考代码:
自行建立数据库
项目结构:
T1_SelectAll.java
package com.czxy.ssm3.test; import com.czxy.ssm3.domain.User; import com.czxy.ssm3.mapper.UserMapper; 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; import java.util.Scanner; /** * @author ChinaManor * #Description T1_SelectAll * #Date: 25/9/2021 20:16 */ public class T1_SelectAll { public static void main(String[] args) throws IOException { //1. 加载配置文件 InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml"); //2 获得工厂 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); //3 通过工程获得连接 SqlSession session = factory.openSession(); //4 获得功能接口 UserMapper mapper = session.getMapper(UserMapper.class); //5 进行查询 String name = null; String password = null; //6 处理数据 System.out.println("请输入用户名和密码"); Scanner sc = new Scanner(System.in); String na = sc.next(); String ps = sc.next(); List<User> users = mapper.selectByNameAndPassword(na, ps); for (User user : users) { if (users!=null) System.out.println(user+"登录成功!"); } session.commit(); //7 释放资源 session.close(); } }
UserMapper.java
package com.czxy.ssm3.mapper; import com.czxy.ssm3.domain.User; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; /** * @author ChinaManor * #Description productMapper * #Date: 25/9/2021 20:16 */ public interface UserMapper { /** * 查询所有 * @return */ @Select("select * from user") public List<User> selectAll(); /* * 查询部分*/ @Select("select * from user2 where username like '%${username}' and password like '%${password}'") public List<User> selectByNameAndPassword(@Param("username") String name,@Param("password") String password); }
运行结果: