其他分享
首页 > 其他分享> > SSM学习-Mybatis开发入门

SSM学习-Mybatis开发入门

作者:互联网

mybatis管理数据

MyUser类

package tradition_user_package;

public class MyUser {
private int uid;
private String uname,usex;
public int getUid() {
	return uid;
}
public void setUid(int uid) {
	this.uid = uid;
}
public String getUname() {
	return uname;
}
public void setUname(String uname) {
	this.uname = uname;
}
public String getUsex() {
	return usex;
}
public void setUsex(String usex) {
	this.usex = usex;
}
public MyUser(int uid, String uname, String usex) {
	super();
	this.uid = uid;
	this.uname = uname;
	this.usex = usex;
}
public MyUser() {
	super();
}
@Override
public String toString() {
	return "MyUser [uid=" + uid + ", uname=" + uname + ", usex=" + usex + "]";
}

}

MyBatisTest类

package tradition_user_package;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			InputStream config=Resources.getResourceAsStream("mybatis-config.xml");
			SqlSessionFactory ssf=new SqlSessionFactoryBuilder().build(config);
			SqlSession ss=ssf.openSession();
			ss.update("tradition_user_package.UserMapper.createTable");
			MyUser mu=ss.selectOne("tradition_user_package.UserMapper.selectUserById",1);
			System.out.println(mu);
			MyUser muadd=new MyUser();
			muadd.setUname("陈恒");
			muadd.setUsex("男");
			ss.insert("tradition_user_package.UserMapper.addUser",muadd);
			MyUser updatemu=new MyUser();
			updatemu.setUid(1);
			updatemu.setUname("张三");
			updatemu.setUsex("女");
			ss.update("tradition_user_package.UserMapper.updateUser",updatemu);
			ss.delete("tradition_user_package.UserMapper.deleteUser",3);
			List<MyUser>lmu=ss.selectList("tradition_user_package.UserMapper.selectAllUser");
			for(MyUser mus:lmu)
				System.out.println(mus);
			ss.commit();
			ss.close();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}

配置文件mybatis-config.xml

<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!-- 使用JDBC的实务管理 -->
<dataSource type="POOLED">
<!-- 数据库驱动系列 -->
<property name="driver" value="com.mysql.jdbc.Driver"></property>
<!-- 连接数据库的URL -->
<property name="url" value="jdbc:mysql://localhost:3306/PD?characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="tradition_user_package/UserMapper.xml"/>
</mappers>
</configuration>

配置文件UserMapper.xml

<?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="tradition_user_package.UserMapper">
<select id="selectUserById" parameterType="Integer"
resultType="tradition_user_package.MyUser">
select * from user where uid = #{uid}
</select>
<select id="selectAllUser" resultType="tradition_user_package.MyUser">
select * from user;
</select>
<insert id="addUser" parameterType="tradition_user_package.MyUser">
insert into user(uname,usex) values(#{uname},#{usex});
</insert>
<update id="updateUser" parameterType="tradition_user_package.MyUser">
update user set uname=#{uname},usex=#{usex} where uid=#{uid} 
</update>
<update id="createTable" >
 create table if not exists User(uid int,uname varchar(50),usex varchar(50));
</update>
<delete id="deleteUser" parameterType="Integer">
delete from user where uid=#{uid}
</delete>
</mapper>

Spring-Mybatis管理数据

使用的jar包
在这里插入图片描述
UserDao接口类

package tradition_user_package;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

@Repository("userDao")
@Mapper
public interface UserDao {
public MyUser selectUserById(Integer uid);
public List<MyUser> selectAllUser();
public int addUser(MyUser user);
public int updateUser(MyUser user);
public int deleteUser(Integer uid);
public void createTable();
}

UserContoller类

package tradition_user_package;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller("userController")

public class UserController {
	@Autowired
	private UserDao userdao;
	public void test() {
	//	TransactionAwareDataSourceProxy
//		SqlSessionFactoryBean ss;
		//MapperScannerConfigurer ss;
		MyUser muser=userdao.selectUserById(2);
		System.out.println(muser);
		System.out.println("================");
	
		MyUser addmu=new MyUser();
		addmu.setUname("陈恒");
		addmu.setUsex("男");
		int add=userdao.addUser(addmu);
		System.out.println("添加了"+add+"条记录");
		System.out.println("================");
		MyUser updatemu=new MyUser();
		updatemu.setUname("张三");
		updatemu.setUsex("女");
		int up=userdao.updateUser(updatemu);
		System.out.println("添加了"+up+"条记录");
		System.out.println("================");
		int dl=userdao.deleteUser(3);
		System.out.println("添加了"+dl+"条记录");
		System.out.println("================");
		List<MyUser>lmu=userdao.selectAllUser();
		for(MyUser mus:lmu)
			System.out.println(mus);
		
	
	}
}

Spirng 配置文件 Ab.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context.xsd
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/tx/spring-tx.xsd
 http://www.springframework.org/schema/aop
 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
 "
 >
<context:component-scan base-package="tradition_user_package"/>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/PD?characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
<property name="maxIdle" value="10"/>
<property name="initialSize" value="5"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- Mapper代理开发,使用Spring自动扫描MyBatis接口并且装配 
Mapper标注的接口-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="tradition_user_package"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!-- 添加事务支持 -->
<tx:annotation-driven transaction-manager="txManager"/>
<bean name="z3" class="Chapter8.HelloBean">
<!-- setter赋值 -->
<property name="name" value="张三"></property>
<property name="course" value="计算机"></property>
<property name="score" value="100"></property>
</bean>
<bean name="ls" class="Chapter8.HelloBean">
<property name="name" value="李四"></property>
<property name="course" value="物理"></property>
<property name="score" value="89"></property>
</bean>
<bean name="w5" class="Chapter8.HelloBean">
<property name="name" value="王五"></property>
<property name="course" value="计算机"></property>
<property name="score" value="90"></property>
</bean>
</beans>

Mybatis配置文件UserMapper.xml

<?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="tradition_user_package.UserDao">
<select id="selectUserById" parameterType="Integer"
resultType="tradition_user_package.MyUser">
select * from user where uid = #{uid}
</select>
<select id="selectAllUser" resultType="tradition_user_package.MyUser">
select * from user;
</select>
<insert id="addUser" parameterType="tradition_user_package.MyUser">
insert into user(uid,uname,usex) values(#{uid},#{uname},#{usex});
</insert>
<update id="updateUser" parameterType="tradition_user_package.MyUser">
update user set uname=#{uname},usex=#{usex} where uid=#{uid} 
</update>
<update id="createTable" >
 create table if not exists User(uid int,uname varchar(50),usex varchar(50));
</update>
<delete id="deleteUser" parameterType="Integer">
delete from user where uid=#{uid}
</delete>
</mapper>

mybatis配置文件mybatis-config.xml

<?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>
<mappers>
<mapper resource="tradition_user_package/UserMapper.xml"/>
</mappers>
</configuration>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>wwwww</display-name>
 
 <context-param>
 <param-name>
contextConfigLocation
</param-name>
<param-value>
classpath:Ab.xml
</param-value>
</context-param>
 <listener>
 <listener-class>
 org.springframework.web.context.ContextLoaderListener
 </listener-class>
 </listener>
 </web-app>

Mybatis Generator 自动生成映射文件
所需jar包 :Mybatis-Generator-core
所需插件:mybatis generator
点击工程右键点击new->others
在这里插入图片描述在这里插入图片描述
确定
generatorConfig.xml内容

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<classPathEntry location="D:\eclipse-workspace\spring\WebContent\WEB-INF\lib\mysql-connector-java-8.0.23.jar"/>
    <context id="mysqlTables">
    <commentGenerator>
    	<property name="suppressAllComments" value="true"/>
    </commentGenerator>
    <jdbcConnection connectionURL="jdbc:mysql://localhost:3306/PD?characterEncoding=utf8" driverClass="com.mysql.jdbc.Driver" password="123456" userId="root" />
    <javaTypeResolver>
    	<property name="forceBigDecimals" value="false"/>
   	</javaTypeResolver>
   	<!-- 生成模型(MyBatis 里面用到的实体类)的包名和位置 -->
    <javaModelGenerator 
    targetPackage="output" 
    targetProject="Spring1\src\main\java" >
    	<property name="enableSubPackages" value="true"/>
    	<property name="trimStrings" value="true"/>
    </javaModelGenerator>
    <!-- 生成的映射文件(MyBatis的SQL语句xml文件)包名和位置-->
    <sqlMapGenerator 
    targetPackage="output" 
    targetProject="Spring1\src\main\java">
    </sqlMapGenerator>
    <!-- 生成实体类Dao包-->
    <javaClientGenerator 
    targetPackage="output" 
    targetProject="Spring1\src\main\java" 
    type="XMLMAPPER" >
    	<property name="enableSubPackage" value="true"/>
    </javaClientGenerator>
    <!-- 生成表(更改tableName和domainObjectName就可以,前提是数据库 PD中的表已经建立) -->
   
    <table tableName="problem"></table>
    <table tableName="user" domainObjectName="user" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
     selectByExampleQueryId="false">
    </table> 
  </context>
</generatorConfiguration>

然后右键该xml文件点击run as 选择Run Mybatis Generator
结果
在这里插入图片描述

标签:入门,MyUser,SSM,uname,user,Mybatis,usex,public,uid
来源: https://blog.csdn.net/m0_55714146/article/details/121571524