<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.bdqn</groupId> <artifactId>ssmDemo</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>ssmDemo Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <!--mybatis依賴--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.2</version> </dependency> <!--mysql數據庫依賴--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.37</version> </dependency> <!--mysql8.0數據庫依賴--> <!-- <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.16</version> </dependency>--> <!--日誌依賴--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> <build> <!--指定mapper存放路徑--> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> <finalName>ssmDemo</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/XXX?useUnicode=true&characterEncoding=UTF-8 ##mysql 8.0版本配置數據源 #driver=com.mysql.cj.jdbc.Driver #url=jdbc:mysql://localhost:3306/test01? serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&useSSL=false userName=XXX password=XXX
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--引入數據源配置文件--> <properties resource="database.properties"/> <!--配置log--> <settings> <setting name="logImpl" value="LOG4J"/> </settings> <typeAliases> <!--實體類位置,默認別名爲首字母小寫--> <package name="com.XXXX.entity" ></package> </typeAliases> <environments default="development"> <environment id="development"> <!--將事物交給jdbc管理--> <transactionManager type="JDBC" /> <!--配置數據源--> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${userName}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> <!--引入mapper文件--> <mappers> <!--引入指定的mapper文件路徑中間用「/」隔開--> <mapper resource="com/XXX/dao/UserDaoMapper.xml"/> <!--引入該路徑下全部的mapper文件用「.」隔開--> <package name="com.XXX.dao"></package> </mappers> </configuration>
### 配置根 ### log4j.rootLogger = debug,console ,fileAppender,dailyRollingFile,ROLLING_FILE,MAIL,DATABASE ### 設置輸出sql的級別,其中logger後面的內容所有爲jar包中所包含的包名 ### log4j.logger.org.apache=dubug log4j.logger.java.sql.Connection=dubug log4j.logger.java.sql.Statement=dubug log4j.logger.java.sql.PreparedStatement=dubug log4j.logger.java.sql.ResultSet=dubug ### 配置輸出到控制檯 ### log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{ 1 }:%L - %m%n ### 配置輸出到文件 ### log4j.appender.fileAppender = org.apache.log4j.FileAppender log4j.appender.fileAppender.File = logs/log.log log4j.appender.fileAppender.Append = true log4j.appender.fileAppender.Threshold = DEBUG log4j.appender.fileAppender.layout = org.apache.log4j.PatternLayout log4j.appender.fileAppender.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n ### 配置輸出到文件,而且天天都建立一個文件 ### log4j.appender.dailyRollingFile = org.apache.log4j.DailyRollingFileAppender log4j.appender.dailyRollingFile.File = logs/log.log log4j.appender.dailyRollingFile.Append = true log4j.appender.dailyRollingFile.Threshold = DEBUG log4j.appender.dailyRollingFile.layout = org.apache.log4j.PatternLayout log4j.appender.dailyRollingFile.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n ### 配置輸出到文件,且大小到達指定尺寸的時候產生一個新的文件 ### log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender log4j.appender.ROLLING_FILE.Threshold=ERROR log4j.appender.ROLLING_FILE.File=rolling.log log4j.appender.ROLLING_FILE.Append=true log4j.appender.ROLLING_FILE.MaxFileSize=10KB log4j.appender.ROLLING_FILE.MaxBackupIndex=1 log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout log4j.appender.ROLLING_FILE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n ### 配置輸出到郵件 ### log4j.appender.MAIL=org.apache.log4j.net.SMTPAppender log4j.appender.MAIL.Threshold=FATAL log4j.appender.MAIL.BufferSize=10 log4j.appender.MAIL.From=chenyl@yeqiangwei.com log4j.appender.MAIL.SMTPHost=mail.hollycrm.com log4j.appender.MAIL.Subject=Log4J Message log4j.appender.MAIL.To=chenyl@yeqiangwei.com log4j.appender.MAIL.layout=org.apache.log4j.PatternLayout log4j.appender.MAIL.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n ### 配置輸出到數據庫 ### log4j.appender.DATABASE=org.apache.log4j.jdbc.JDBCAppender log4j.appender.DATABASE.URL=jdbc:mysql://localhost:3306/test log4j.appender.DATABASE.driver=com.mysql.jdbc.Driver log4j.appender.DATABASE.user=root log4j.appender.DATABASE.password= log4j.appender.DATABASE.sql=INSERT INTO LOG4J (Message) VALUES ('[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n') log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout log4j.appender.DATABASE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n log4j.appender.A1=org.apache.log4j.DailyRollingFileAppender log4j.appender.A1.File=SampleMessages.log4j log4j.appender.A1.DatePattern=yyyyMMdd-HH'.log4j' log4j.appender.A1.layout=org.apache.log4j.xml.XMLLayout
public class TestStudent { public static void main(String[] args) { //讀取配置文件 String resource="mybatis-config.xml"; InputStream is = null; try{ is = Resources.getResourceAsStream(resource); }catch (Exception e){ } SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); //true爲自動提交事物 false手動提交事物 事物提交方法session.commit(); SqlSession session = factory.openSession(true); //獲取全部學生教室(trim) //List<Student> studentList=session.selectList("com.XXX.dao.StudentMapper.getAllStudent"); List<Student> studentList=session.getMapper(StudentMapper.class).getAllStudent(1); for (Student stu: studentList) { System.out.println("學生id"+stu.getId()+"學生姓名"+stu.getName()); for (ClassRoom room:stu.getStudentList()) { System.out.println("教室id"+room.getTid()+"教室名稱"+room.getClassRoom()); } } //測試foreach 參數爲數組 Integer[] id={1,2}; List<Student> studentArray=session.getMapper(StudentMapper.class).getAllStudent_array(id); for (Student stu: studentArray) { System.out.println("學生id"+stu.getId()+"學生姓名"+stu.getName()); for (ClassRoom room:stu.getStudentList()) { System.out.println("教室id"+room.getTid()+"教室名稱"+room.getClassRoom()); } } //測試foreach 參數爲集合 List<Integer> list=new ArrayList<Integer>(); list.add(1); list.add(2); List<Student> studentList1=session.getMapper(StudentMapper.class).getAllStudent_list(list); for (Student stu: studentList1) { System.out.println("學生id"+stu.getId()+"學生姓名"+stu.getName()); for (ClassRoom room:stu.getStudentList()) { System.out.println("教室id"+room.getTid()+"教室名稱"+room.getClassRoom()); } } //測試foreach 參數爲map Map<String,Object> map=new HashMap<String,Object>(); List<Integer> listId=new ArrayList<Integer>(); list.add(1); list.add(2); map.put("name","張三"); map.put("list",listId); map.put("start",0); map.put("pageSize",2); List<Student> allStudentMap=session.getMapper(StudentMapper.class).getAllStudent_map(map); for (Student stu: allStudentMap) { System.out.println("學生id"+stu.getId()+"學生姓名"+stu.getName()); for (ClassRoom room:stu.getStudentList()) { System.out.println("教室id"+room.getTid()+"教室名稱"+room.getClassRoom()); } } } }
public class Student { private int id; private String name; //一對多關係 private List<ClassRoom> studentList; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setStudentList(List<ClassRoom> studentList) { this.studentList = studentList; } public List<ClassRoom> getStudentList() { return studentList; } }
public class ClassRoom { private int tid; private int studentId; private String classRoom; public int getTid() { return tid; } public void setTid(int tid) { this.tid = tid; } public int getStudentId() { return studentId; } public void setStudentId(int studentId) { this.studentId = studentId; } public String getClassRoom() { return classRoom; } public void setClassRoom(String classRoom) { this.classRoom = classRoom; } }
Dao接口html
public interface StudentMapper { List<Student> getAllStudent(@Param("id")Integer id); //查詢全部學生的所屬教室(數組) List<Student> getAllStudent_array(Integer[] id); //查詢全部學生的所屬教室(集合) List<Student> getAllStudent_list(List<Integer> id); //查詢全部學生的所屬教室(map) List<Student> getAllStudent_map(Map<String,Object> id); }
Mapper映射文件:java
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.XXX.dao.StudentMapper"> <!--關係映射--> <resultMap id="getClassRoom" type="student"> <id property="id" column="id"></id> <result column="name" property="name"></result> <collection property="studentList" ofType="ClassRoom"> <id property="tid" column="tid"></id> <result column="studentId" property="studentId"></result> <result column="classRoom" property="classRoom"></result> </collection> </resultMap> <!--trim+if動態sql--> <select id="getAllStudent" resultMap="getClassRoom" > select * from student s left join classRoom c on s.id=c.studentId <trim prefix="where"> <if test="id!=null"> s.id=#{id} </if> </trim> </select> <select id="getAllStudent_array" resultMap="getClassRoom"> select * from student s left join classRoom c on s.id=c.studentId where s.id in <foreach collection="array" item="id" open="(" separator="," close=")"> #{id} </foreach> </select> <select id="getAllStudent_list" resultMap="getClassRoom"> select * from student s left join classRoom c on s.id=c.studentId where s.id in <foreach collection="list" item="id" open="(" separator="," close=")"> #{id} </foreach> </select> <select id="getAllStudent_map" resultMap="getClassRoom"> select * from student s left join classRoom c on s.id=c.studentId where s.name=#{name} or s.id in <foreach collection="list" item="id" open="(" separator="," close=")"> #{id} </foreach> order by c.tid desc limit #{start},#{pageSize} </select> </mapper>
public class User { private int id; private String name; private String password; //一對一關係映射 private Role roleId; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public void setRoleId(Role roleId) { this.roleId = roleId; } public Role getRoleId() { return roleId; } @Override public String toString() { return "id"+id+"姓名"+name+"密碼"+password+"角色名"+getRoleId().getRoleName(); } }
public class Role { private String roleName; private int id; public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
public interface UserDaoMapper { //獲取總數 int countUser(); //查詢全部對象 List<User> getAllUser(); //添加對象 int addUser(User user); //經過id刪除對象 int deleteUser(@Param("id")int id); //查詢對象角色 List<User> getAllUserRole(); }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.XXX.dao.UserDaoMapper"> <resultMap id="user" type="user"> <id column="id" property="id"></id> <result property="name" column="name"></result> <result property="password" column="password"></result> <association property="roleId" javaType="role"> <id column="id" property="id"></id> <result column="roleName" property="roleName"></result> </association> </resultMap> <select id="countUser" resultType="int"> select count(1) from user </select> <select id="getAllUser" resultType="user"> select * from user </select> <insert id="addUser" parameterType="user"> insert into user(name,password) values(#{name},#{password}) </insert> <delete id="deleteUser"> delete from user where id=#{id} </delete> <select id="getAllUserRole" resultMap="user"> select * from USER u left join role r on u.roleId=r.id </select> </mapper>
public class Test1 { private static SqlSessionFactory factory; static { String resource="mybatis-config.xml"; InputStream is = null; try{ is = Resources.getResourceAsStream(resource); }catch (Exception e){ } factory = new SqlSessionFactoryBuilder().build(is); } public static SqlSession createSqlSession(){ //factory.openSession(false) 參數是false 手動提交事物 true 自動提交事物 return factory.openSession(false); } public static void main(String[] args) { //查詢 SqlSession session=Test1.createSqlSession(); //測試方法一 // List<User> userList=session.getMapper(UserDaoMapper.class).getAllUser(); //測試方法二 List<User> userList=session.selectList("com.XXX.dao.UserDaoMapper.getAllUser"); /* for (User user:userList) { System.out.println(user); }*/ //刪除 // session.getMapper(UserDaoMapper.class).deleteUser(75); // session.commit(); //查詢角色 List<User> userRoleList=session.selectList("com.XXXX.dao.UserDaoMapper.getAllUserRole"); for (User user:userRoleList) { System.out.println(user); } } }
public class Test { public static void main(String[] args) { String resource="mybatis-config.xml"; InputStream is = null; try{ is = Resources.getResourceAsStream(resource); }catch (Exception e){ } SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); SqlSession session = factory.openSession(true); int result = session.selectOne("com.bdqn.dao.UserDaoMapper.countUser"); System.out.println(result); List<User> userList = session.selectList("com.XXXX.dao.UserDaoMapper.getAllUser"); System.out.println(userList.get(0)); User user=new User(); user.setName("張三"); user.setPassword("123456"); int addResult=session.insert("com.XXXX.dao.UserDaoMapper.addUser",user); // session.commit(); System.out.println(addResult); } }