《partner4java 讲述MyBatis入门》之第二步:MyBatis 常用标签

WebSphere数据源中的连接被意外关闭案例 频繁创建连接的现象前阵子维护反馈说,oracle数据库每秒创建连接数过高,而主要来源来自于WebSphere集群所在的主机。 按理说,使用连接池的应用,连接是不会很频繁的。追溯一下所在主机的程序,发现可疑对象是一个使用jdbc轮子的应用。 就是自己写了一套代码封装了jdbc操作,虽然连接是从数据源中获取的。但是,单纯看代码,的确没发现有什么问题,该关闭的地方也关闭,不存在泄露的情况。再说,这种现 阅读详情

(导读:MyBatis系列内容仅供技术参考和技术储备。因本人目前未在项目中进行实战,可能会出现一些知识误导,还请谅解。本文大量参考了官方文档,如果和官方文档有偏差,请以官方文档为准)

主配置文件详解

(我们本章节主要讲解的mybatis-config.xml各配置)
Configuration
The MyBatis configuration contains settings and properties that have a dramatic effect on how MyBatis behaves. The high level structure of the document is as follows:
·configuration
· properties
·property
· settings
· typeAliases
· typeHandlers
· objectFactory
· plugins
· environments
 ·environment
·transactionManager
·dataSource
· databaseIdProvider
· mappers

(我们下面讲解的各标签在mybatis-config.xml文件添加顺序是固定的,不能打乱:
- The content of element type "configuration" must match 
"(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,proxyFactory?,plugins?,environments?,databaseIdProvider?,mappers?)".
- Start tag of element <configuration>)

4.1 properties -- 参数值

三种方式:
1、引入指定文件
<properties resource="mysql.properties" />
<properties>元素允许在主配置文件之外提供一个properties格式对应文件,从而使得主配置文件更加通用。这样对部署非常有用。
两个属性
resource--类路径上的一个资源
url -- 统一资源定位符
最后通过名称来引用这些属性。

2、内部配置
property:
这是通过外部文件引入的方式,我们可以在properties内创建内部property元素,如:
<properties resource="org/mybatis/example/config.properties">
<property name="username" value="dev_user"/>
<property name="password" value="F2Fa3!33TYyg"/>
</properties>

3、在Java代码中传入
Properties can also be passed into the SqlSessionBuilder.build() methods. For example:
SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader, props);
// ... or ...
SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader, environment, props);

使用方式:
然后可以使用配置文件里的属性值或者使用内部方式加入的属性值,来给为配置文件进行动态配置:

<dataSource type="POOLED">
	<property value="${driver}" name="driver" />
	<property value="${url}" name="url" />
	<property value="${username}" name="username" />
	<property value="${password}" name="password" />
</dataSource>
在这个例子中的用户名和密码等将被替换成属性元素中设置的值。

问题:
当上面三种方式出现重复的值如何处理?
首先他们三者的加载顺序是:内部配置 --> 引入指定文件 --> 在Java代码中传入。若在加载过程中出现重复值,后者会覆盖前者。

4.2 settings -- 全局配置

<settings>元素添加若干属性来设置这些可选项。MyBatis有许多配置项可用,并且每个配置项对于这个SQLMap实例来说都是全局的。
这些都是非常重要的配置,用于指定MyBatis在运行时的行为。如果不指定,会使用默认值。

<settings>

		<!-- 在全局范围内"启用或禁用任何高速缓存" - 应该是除了session;默认值true -->
		<setting name="cacheEnabled" value="true" />

		<!-- 延迟加载是一种只加载必要信息而推迟加载其他未明确请求的数据的技术。也就是说,除非绝对需要,否则应用程序加载的数据越少越好。 lazyLoadingEnabled配置项用于指定当存在相关联的已映射语句时,"是否使用延迟加载"。其有效值为true或false,默认值为true。 -->
		<!-- <setting name="lazyLoadingEnabled" value="true" /> -->

		<!-- 开启懒加载。默认值为true -->
		<!-- <setting name="aggressiveLazyLoading" value="true" /> -->

		<!-- 指定对象中什么方法会触发延迟加载。值为以逗号分隔的方法名称列表。 -->
		<!-- <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString" 
			/> -->

		<!-- 是否允许一个statement返回多个ResultSets,但是需要驱动程序支持。默认值true -->
		<setting name="multipleResultSetsEnabled" value="true" />

		<!-- 是否可以使用别名获取,具体取决于驱动程序是否支持。默认为true -->
		<setting name="useColumnLabel" value="true" />

		<!-- 允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行(比如Derby)。默认值false -->
		<!-- <setting name="useGeneratedKeys" value="false" /> -->

		<!-- 指定是否以及如何自动映射数据字段到POJO字段。三个选项:NONE不自动映射;PARTIAL将只自动映射简单的,没有嵌套的结果;FULL将自动映射任何(包含嵌套或以其他方式)复杂的结果。默认值PARTIAL -->
		<setting name="autoMappingBehavior" value="PARTIAL" />

		<!-- 默认执行方式。三种方式:SIMPLE默认没有特殊处理;REUSE重用PreparedStatements;BATCH重用statements和进行批量更新。默认值:SIMPLE -->
		<setting name="defaultExecutorType" value="SIMPLE" />

		<!-- 设置Statement默认数据库响应超时时间,单位为妙。 -->
		<setting name="defaultStatementTimeout" value="1" />

		<!-- 嵌套结果映射,是否使用rowbounds进行分页,建议不要使用rowbounds进行分页,特别是SQL执行返回结果很大的情况下(因为它用的是返回后截取-逻辑分页)。默认值false -->
		<setting name="safeRowBoundsEnabled" value="false" />

		<!-- 进行自动映射时,数据以下划线命名,如数据库返回的"order_address"命名字段是否映射为class的"orderAddress"字段。默认为false -->
		<setting name="mapUnderscoreToCamelCase" value="false" />

		<!-- MyBatis使用本地缓存来提高重复查询的速度。两个选项:SESSION,和我们hibernate里的session类似,在同一个session中共享;STATEMENT,只在同一个statement中共享。默认值SESSION -->
		<setting name="localCacheScope" value="SESSION" />

		<!-- 有些驱动程序在返回值为NULL时需要指定JDBC类型,大部分情况下是:NULL、VARCHAR或OTHER。默认值OTHER -->
		<setting name="jdbcTypeForNull" value="OTHER" />

	</settings>



4.3 typeAliases -- 别名

一个type alias是为一个Java Type定义的短名称。
除非别无选择,否则没人愿意输入像这样一个长串的名字:com.partner4java.demo.entity.Account。
<typeAlias>元素允许定义别名,这样就可以直接用account来代替刚才的那个冗长的全限定类名了。
<typeAlias alias="user" type="com.partner4java.demo2.User" />
当在配置过程中定义account这个别名之后,就可以在任何时候使用他了,每当你必须提供一个数据类型时,都可以使用全限定类名或者别名来告诉iBATIS你想使用哪个数据。
iBATIS为若干类型定义了别名,以免除开发人员必须手工添加这些别名的麻烦。
Demo:
<!-- 注意一点,这个放在properties后面,不然会加载出错 -->
<typeAliases>
<typeAlias alias="user" type="com.partner4java.demo2.User" />
</typeAliases>

我们加了上面别名之后,就可以修改User.xml文件的返回类型<select id="selectUser" resultType="user">

我们可以使用更简洁的方式,指定一个包,MyBatis会自动扫描包下的所有类,以非限定类名首字母小写来作为别名,当然你也可以使用@Alias注解手工指定:
<!-- mybatis-config.xml -->
<typeAliases>
	<package name="com.partner4java"/>
</typeAliases>

@Alias("user")
public class User {
	...
}

There are many built-in type aliases for common Java types. They are all case insensitive, note the
special handling of primitives due to the overloaded names.
Alias Mapped Type
_byte byte
_long long
_short short
_int int
_integer int
_double double
_float float
_boolean boolean
string String
byte Byte
long Long
short Short
int Integer
integer Integer
double Double
float Float
boolean Boolean
date Date
decimal Decimal
bigdecimal  BigDecimal
object Object
map Map
hashmap HashMap
list List
arraylist ArrayList
collection Collection
iterator Iterator

(学习到这里,你应该转到“自动映射”,学完自动映射然后再返回这里)

4.4 typeHandlers -- 类型处理器

MyBatis使用类型处理器(type handler)将数据从数据库特定的数据类型转换为应用程序中的数据类型,这样你就可以创建一个以一种尽可能透明的方式来使用数据库的应用程序。
类型处理器本质上就是一个翻译器(translator)--他将数据库返回的结果集合中的列“翻译”为相应的JavaBean中的字段。

MyBatis自带的类型处理器:
Type Handler Java Types JDBC Types
BooleanTypeHandler java.lang.Boolean,booleanAny compatible BOOLEAN
ByteTypeHandler java.lang.Byte, byte Any compatible NUMERIC or BYTE
ShortTypeHandler java.lang.Short, short Any compatible NUMERIC or SHORT INTEGER
IntegerTypeHandler java.lang.Integer, int Any compatible NUMERIC or INTEGER
LongTypeHandler java.lang.Long, long Any compatible NUMERIC or LONG INTEGER
FloatTypeHandler java.lang.Float, float Any compatible NUMERIC or FLOAT
DoubleTypeHandler java.lang.Double, double Any compatible NUMERIC or DOUBLE
BigDecimalTypeHandler java.math.BigDecimal Any compatible NUMERIC or DECIMAL
StringTypeHandler java.lang.String CHAR, VARCHAR
ClobTypeHandler java.lang.String CLOB, LONGVARCHAR
NStringTypeHandler java.lang.String NVARCHAR, NCHAR
NClobTypeHandler java.lang.String NCLOB
ByteArrayTypeHandler byte[] Any compatible byte stream type
BlobTypeHandler byte[] BLOB, LONGVARBINARY
DateTypeHandler java.util.Date TIMESTAMP
DateOnlyTypeHandler java.util.Date DATE
TimeOnlyTypeHandler java.util.Date TIME
SqlTimestampTypeHandler java.sql.Timestamp TIMESTAMP
SqlDateTypeHandler java.sql.Date DATE
SqlTimeTypeHandler java.sql.Time TIME
ObjectTypeHandler Any OTHER, or unspecified
EnumTypeHandler Enumeration Type VARCHAR any string compatible type, as the code is stored (not the index).
EnumOrdinalTypeHandler Enumeration Type Any compatible NUMERIC or DOUBLE, as the position is stored(not the code itself).

你可以覆盖上面的类型处理器,也可以自定义一个类型处理器。
如果这么做,你只需要三步:
1、写一个类继承自org.apache.ibatis.type.BaseTypeHandler;
2、使用@MappedJdbcTypes注解给该类指定要处理的类型;
3、在XML中配置一个本类的<typeHandler>标签,然后指定扫描指定包内的。
Demo:
// ExampleTypeHandler.java
@MappedJdbcTypes(JdbcType.VARCHAR)
public class ExampleTypeHandler extends BaseTypeHandler<String> {
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType ps.setString(i, parameter);
	}
	@Override
	public String getNullableResult(ResultSet rs, String columnName) throws SQLException return rs.getString(columnName);
	}
	@Override
	public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException return rs.getString(columnIndex);
	}
	@Override
	public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException return cs.getString(columnIndex);
	}
}


<typeHandlers>
	<typeHandler handler="org.mybatis.example.ExampleTypeHandler"/>
</typeHandlers>


第2步你也可以省略,在<typeHandler>标签中使用jdbcType属性指定。
第3步如果你想扫描指定包下的所有带有@MappedJdbcTypes注解的类为类型处理器,不单独声明,可替换为:
<!-- mybatis-config.xml -->
<typeHandlers>
<package name="org.mybatis.example"/>
</typeHandlers>

4.5 objectFactory

Each time MyBatis creates a new instance of a result object, it uses an ObjectFactory instance to do so. 
The default ObjectFactory does little more than instantiate the target class with a default constructor, or a parameterized constructor if parameter mappings exist. 
If you want to override the default behaviour of the ObjectFactory, you can create your own. For example:
// ExampleObjectFactory.java
public class ExampleObjectFactory extends DefaultObjectFactory {
	public Object create(Class type) {
		return super.create(type);
	}
	public Object create(Class type, List<Class> constructorArgTypes, List<Object> constructorArgs) return super.create(type, constructorArgTypes, constructorArgs);
	}
	public void setProperties(Properties properties) {
		super.setProperties(properties);
	}
}

<!-- mybatis-config.xml -->
<objectFactory type="org.mybatis.example.ExampleObjectFactory">
	<property name="someProperty" value="100"/>
</objectFactory>

The ObjectFactory interface is very simple. It contains two create methods, one to deal with the
default constructor, and the other to deal with parameterized constructors. Finally, the setProperties
method can be used to configure the ObjectFactory. Properties defined within the body of the
objectFactory element will be passed to the setProperties method after initialization of your
ObjectFactory instance.

4.6 plugins

不做讨论,当你对MyBatis足够熟悉的时候可以自行研究。


4.7 environments -- 多数据源配置

environment:
MyBatis的可配置多个环境。
这可以帮助你解决应用场景中很多问题。
例如,你可能有不同的配置,为您的开发,测试和生产环境。
(但是,在你使用时只能选择其中一种)
Demo:
<!-- 配置数据源相关的信息 -->
<environments default="demo1">
	<environment id="demo1">
		<transactionManager type="JDBC" />
		<dataSource type="POOLED">
			<property value="${driver}" name="driver" />
			<property value="${url}" name="url" />
			<property value="${username}" name="username" />
			<property value="${password}" name="password" />
		</dataSource>
	</environment>
	<environment id="demo2">
		<transactionManager type="JDBC" />
		<dataSource type="POOLED">
			<property value="${driver}" name="driver" />
			<property value="${url}" name="url" />
			<property value="${username}" name="username" />
			<property value="${password}" name="password" />
		</dataSource>
	</environment>
</environments>

比如上面这个,他会默认使用demo1,但是你如果想代码指定demo2,可以调用SqlSessionFactoryBuilder().build(InputStream inputStream, String environment)接收String类型environment参数的方法。

<transactionManager>元素:
由于MyBatis就是为了使数据库访问变得更加简单而设计的,因此他将为你处理所有的数据库事务。
使用MyBatis时,有哪些事务管理器实现类是可用的。可以考虑使用MyBatis那些预定义的事务管理器。
<transactionManager>元素的type属性就是用于指定应该使用哪个事务管理器的。
iBATIS提供了若干内建事务管理器实现:
JDBC 用于提供简单的基于jdbc的事务管理。大多数情况下,使用这个事务管理器就足够了。
EXTERNAL 用于提供非事务管理,并假定管理事务的是应用程序,而不是MyBatis

对于事务管理器,另一个可用的设置就是commitRequired属性,该属性可被设置为true或者false,默认是为false。
他主要用于那些要求在释放某个连接之前必须提交(commit)或者回退(rollback)的情况。
对于某些操作(例如选择和存储过程调用),通常并不需要事务,因此一般会将其忽略。
某些数据库驱动程序(例如Sybase驱动程序)不会轻易释放连接,直至该连接的每个已启动事务都已提交或回退。在这些情况下,就可以使用commitRequired属性来强制释放连接,即使在那些通常需要在一个事务中释放却没用释放的情况。

<dataSource>元素
在java中,使用连接池的标准方法就是通过javax.sql.DataSource对象。
事务管理的<dataSource>元素有一个属性,用来告诉MyBatis他应该为其数据源工厂实例化并使用哪个类。
<dataSource>元素名字很容易仍人产生误解,因为实际上他并不是用来定义DataSource,而是用来定义DataSourceFactory实现类,MyBatis将用这个实现类来创建实际的DataSource。
MyBatis具有三种数据源工厂实现类:
UNPOOLED -- 最简单的方式,没有加入连接池
有五个基本配置:
·driver – This is the fully qualified Java class of the JDBC driver (NOT of the DataSource class
if your driver includes one).
· url – This is the JDBC URL for your database instance.
·username – The database username to log in with.
·password - The database password to log in with.
·defaultTransactionIsolationLevel – The default transaction isolation level for
connections.
Optionally, you can pass properties to the database driver as well. To do this, prefix the properties
with driver., for example:
·driver.encoding=UTF8
This will pass the property encoding, with the value UTF8, to your database driver via the
DriverManager.getConnection(url, driverProperties) method.

POOLED -- 这是一个加入了连接池策略的的方式
在上面五个基本配置外又增加了:
·poolMaximumActiveConnections – This is the number of active (i.e. in use) connections that
can exist at any given time. Default: 10
·poolMaximumIdleConnections – The number of idle connections that can exist at any given
time.
·poolMaximumCheckoutTime – This is the amount of time that a Connection can be "checked
out" of the pool before it will be forcefully returned. Default: 20000ms (i.e. 20 seconds)
·poolTimeToWait – This is a low level setting that gives the pool a chance to print a log status
and re-attempt the acquisition of a connection in the case that it’s taking unusually long (to avoid
failing silently forever if the pool is misconfigured). Default: 20000ms (i.e. 20 seconds)
·poolPingQuery – The Ping Query is sent to the database to validate that a connection is in
good working order and is ready to accept requests. The default is "NO PING QUERY SET",
which will cause most database drivers to fail with a decent error message.
·poolPingEnabled – This enables or disables the ping query. If enabled, you must also set the
poolPingQuery property with a valid SQL statement (preferably a very fast one). Default: false.
·poolPingConnectionsNotUsedFor – This configures how often the poolPingQuery
will be used. This can be set to match the typical timeout for a database connection, to
avoid unnecessary pings. Default: 0 (i.e. all connections are pinged every time – but only if
poolPingEnabled is true of course).

JNDI -- This implementation of DataSource is intended for use with containers such as EJB or
Application Servers that may configure the DataSource centrally or externally and place a reference to
it in a JNDI context. This DataSource configuration only requires two properties:
·initial_context – This property is used for the Context lookup from the InitialContext
(i.e. initialContext.lookup(initial_context)). This property is optional, and if omitted, then the
data_source property will be looked up against the InitialContext directly.
·data_source – This is the context path where the reference to the instance of the DataSource
can be found. It will be looked up against the context returned by the initial_context lookup, or
against the InitialContext directly if no initial_context is supplied.
Similar to the other DataSource configurations, it’s possible to send properties directly to the
InitialContext by prefixing those properties with env., for example:
·env.encoding=UTF8
This would send the property encoding with the value of UTF8 to the constructor of the
InitialContext upon instantiation.


4.8 databaseIdProvider -- 不同库SQL匹配

我们可以配置不同数据库的不同SQL,会根据数据库引擎进行决定。
<databaseIdProvider type="VENDOR">
<property name="SQL Server" value="sqlserver"/>
<property name="DB2" value="db2"/>
<property name="Oracle" value="oracle" />
</databaseIdProvider>


4.9 mappers -- 引入SQL

前面我们已经提到了,有两种使用方式:
1、在XML中配置SQL,需要挨个在mybatis-config.xml中指定
如:
<mappers>
	<mapper resource="com/partner4java/demo2/User.xml" />
</mappers>

2、使用注解管理SQL,直接指定要扫描的jar包
<mappers>
	<!-- 指定扫描指定目录的注解 -->
	<package name="com.partner4java" />
</mappers>

public interface UserMapper {
	//我们用到了注解@Select,参数问SQL
	@Select("select * from user where id = #{id}")
	public User selectUserByID(int id);
}


自动映射

从数据库中获取数据是一个应用程序中最基本的操作之一。MyBatis框架使得编写大部分的SELECT语句都毫不费力,并且提供了很多特性,使得你几乎可以从数据库中得到任何想要的数据。

1.使用XML
正如我们helloworld里面的一样,在XML中配置select语句。
查询参数替代(#{})符号。

<!-- User.xml -->
<!-- parameterType为我们参数类型 -->
<select id="selectUserByID" resultType="user" parameterType="int">
	select * from user where id = #{value}
</select>

public static void main(String[] args) {
	InputStream is = null;
	SqlSessionFactory sqlSessionFactory = null;
	SqlSession session = null;
	try {
		is = Resources.getResourceAsStream("mybatis-config4.xml");
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
		session = sqlSessionFactory.openSession();
		//执行一个唯一返回值的查询;user.selectUserByID由两部分组成:“user.”为我们的namespace;“selectUserByID”为我们具体id。
		User user = session.selectOne("user.selectUserByID", 1);
		System.out.println(user);
	} catch (IOException e) {
		e.printStackTrace();
	}finally{
		try {
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
	}
}


问题:MyBatis框架是如何处理该语句的?
首先,MyBatis将查找名为user.selectUserByID的已映射语句,并把#{value}占位符变换为一个预备语句参数,就是转换成我们JDBC中所用的"?"格式。

2.使用注解的方式
我们的User.xml就不需要了,但是需要额外两步操作:
配置mybatis-config.xml
<mappers>
	<!-- 指定扫描指定目录的注解 -->
	<package name="com.partner4java" />
</mappers>

新建Mapper接口类:
(Mapper接口只是定义了各种查询的格式,含义很容易理解,方法参数就是为我们的SQL输入参数,返回值为SQL返回封装类型)
public interface UserMapper {
	//我们用到了注解@Select,参数问SQL
	@Select("select * from user where id = #{id}")
	public User selectUserByID(int id);
}

执行:
is = Resources.getResourceAsStream("mybatis-config5.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
session = sqlSessionFactory.openSession();
//指定全类名,加方法
User user = session.selectOne("com.partner4java.demo2.UserMapper.selectUserByID", 1);
System.out.println(user);

上面的执行,我们还可以进行修改,给session指定一个默认的Mapper接口类(这样每次执行都不需要再给全类名了,更简洁):
is = Resources.getResourceAsStream("mybatis-config5.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
session = sqlSessionFactory.openSession();
// 指定我们本session加载那个Mapper接口类
session.getMapper(UserMapper.class);
// 现在就只需要指定方法名
User user = session.selectOne("selectUserByID", 1);
System.out.println(user);

3.自动结果映射
你可能已经注意到了,在所有我们给出的示例中都没有定义任何结果映射(result map),但是确实定义了结果类(result class)。
这种方式可行是因为MyBatis的自动结果映射机制,该机制会在已映射语句第一次被执行时,迅速的自动创建一个结果映射,然后将它应用于这条已映射语句。
可以有3种方式来使用这个特性:单列选择(single-column selection),固定多列选择(fixed-column list selection)和动态多列选择(dynamic-column list selection)。

单列选择 --
如果只想从某个查询中获取单例,就可以使用别名value作为一种快捷方式来完成此目的,这样就可以不需要定义复杂的结果映射了,只需要指定resultType:
<select id="selectUsernameByID" resultType="string" parameterType="int">
select username from user where id = #{value}
</select>

固定多列选择 -- 
如果需要查询多列,就可以使用自动结果映射来告诉MyBatis将列名作为bean的特性名,或者作为Map键。
当以这种方式映射到bean时,需要牢记一点:如果所选择的列在数据库中存在,但是不存在于你要映射的bean中,你将不会得到任何错误或警告,但是也得不到任何数据--这些数据只会静静的被忽略。
映射到Map对象时,也有相似的问题:尽管你仍然可以得到数据,但是这些数据不会在你所期望的地方。

动态多列选择 -- 
如果语句中被选择的那些字段列表可以在运行时改变,那么也可以使用动态结果映射。
(后面章节我们再具体说动态映射)

4.联结相关数据
有时候出于制作报表或者其他的什么目的,你可能想要把多个数据表联结起来,形成一个平板型结构。
MyBatis框架可以让你毫不费力地完成这项工作,因为它是将SQL语句映射为对象,而不是将数据库中的表映射为对象,所以映射表查询和映射多表查询几乎没有什么不同。


作用范围和生命周期

和Hibernate一样,我们类似Session各种资源的作用范围和生命周期是很重要的。

SqlSessionFactoryBuilder:
这个类在创建SqlSessionFactory之后没必要保持其“生命”,因为在创建了所需的SqlSessionFactory之后SqlSessionFactoryBuilder就没有任何作用。
SqlSessionFactoryBuilder建议在方法内使用即可,这样它的声明周期即为该方法执行过程。
保证其及时释放的意义在于,SqlSessionFactoryBuilder内持有了很多解析后的XML数据。

SqlSessionFactory:
创建SqlSession的工厂类。
犹如我们常用的工厂类,工厂是不建议销毁的,因为它要一直不断给我们创建所需对象。
最好的处理方式就是把SqlSessionFactory设置为单例的。

SqlSession:
每个线程都应该有自己的SqlSession实例。
SqlSession的实例不能共享,不是线程安全的。
因此,最好的范围是请求或方法的范围。
不要让一个SqlSession实例的引用一个静态字段,甚至一个类的实例字段。
在会话结束时,你要确保它的及时正确关闭。
如:
SqlSession session = sqlSessionFactory.openSession();
try {
// do work
} finally {
session.close();
}

Mapper Instances:
映射器是您创建的绑定映射statements的接口。
从SqlSession实例的映射接口收购。
它的生命周期是依附于SqlSession,因此不需要自己主动销毁。
映射器实例的最佳范围是方法范围(同SqlSession)。
也就是说,它在方法被请求时生效,被用于在该方法内,然后伴随方法结束时丢弃。
如:
SqlSession session = sqlSessionFactory.openSession();
try {
BlogMapper mapper = session.getMapper(BlogMapper.class);
// do work
} finally {
session.close();
}


Mapper XML Files 基础篇

1.Mapper XML Files
首先还是那句话MyBatis与O/RM不同:他不是直接把类映射为数据库表或者说把类的字段映射为数据库列,而是“把SQL语句的参数和结果映射为类”。
所以,我们主要的工作就是书写维护SQL。我们使用单独的XML文件维护一组相关SQL。也就是我们接下来学习的知识。
首先根元素为<mapper>,这是“奇迹”发生的地方,如果你和JDBC代码对比,你会立即看到节省了95%的代码,且它以SQL为核心,让我们可以寻求极致完美的完成自己的项目。

(我们这里不再一一阐述SqlSession的各方法作用,如果你学过JDBC,根据方法名很容易猜想作用,如果没学过JDBC请参考 http://blog.csdn.net/partner4java/article/details/8213119)

Mapper XML文件中只有很少数的一级标签:
·cache – 给定命名空间的缓存配置.
·cache-ref – 从另一个命名空间引用缓存配置.
·resultMap – 这些标签中最强大最复杂的标签,描述如何把返回的数据结果封装成Java对象.
·parameterMap – 已过时(用于描述Java对象如何对应数据库占位符).
·sql – 元素用于创建一个文本片段,而这些文本片段又可以组合起来以创建完整的SQL语句。.
·insert – A mapped INSERT statement.
·update – A mapped UPDATE statement.
·delete – A mapped DELETE statement.
·select – A mapped SELECT statement.

接下来的章节将详细描述这些元素:

·select
select将是我们最常用的元素,不过不用担心,因为它使用起来很简单。
For example:
<select id="selectPerson" parameterType="int" resultType="hashmap">
SELECT * FROM PERSON WHERE ID = #{id}
</select>
This statement is called selectPerson, takes a parameter of type int (or Integer), and returns a
HashMap keyed by column names mapped to row values.

Notice the parameter notation:
#{id}
This tells MyBatis to create a PreparedStatement parameter. With JDBC, such a parameter would be
identified by a "?" in SQL passed to a new PreparedStatement, something like this:
// Similar JDBC code, NOT MyBatis…
String selectPerson = "SELECT * FROM PERSON WHERE ID=?";
PreparedStatement ps = conn.prepareStatement(selectPerson);
ps.setInt(1,id);

在你使用MyBatis时上面的代码就不需要你写了,这也是我们使用MyBatis的原因。不过MyBatis帮你做的不仅如此,还包含结果的获取封装,这个只是我们后面会讲解。

The select element has more attributes that allow you to configure the details of how each statement should behave.
<select
id="selectPerson"
parameterType="int"
parameterMap="deprecated"
resultType="hashmap"
resultMap="personResultMap"
flushCache="false"
useCache="true"
timeout="10000"
fetchSize="256"
statementType="PREPARED"
resultSetType="FORWARD_ONLY">

Attribute Description
--------------------------------------------------------------------------
id A unique identifier in this namespace that can be used
to reference this statement.

parameterType The fully qualified class name or alias for the
parameter that will be passed into this statement.

parameterMap This is a deprecated approach to referencing an
external parameterMap. Use inline parameter
mappings and the parameterType attribute.

resultType The fully qualified class name or alias for the expected
type that will be returned from this statement. Note
that in the case of collections, this should be the
type that the collection contains, not the type of the
collection itself. Use resultType OR resultMap,
not both.

resultMap A named reference to an external resultMap.
Result maps are the most powerful feature of MyBatis,
and with a good understanding of them, many difficult
mapping cases can be solved. Use resultMap OR
resultType, not both.


flushCache Setting this to true will cause the local and 2nd level
caches to be flushed whenever this statement is
called. Default: false for select statements.


useCache Setting this to true will cause the results of this
statement to be cached in 2nd level cache. Default:
true for select statements.


timeout This sets the number of seconds the driver will wait for
the database to return from a request, before throwing
an exception. Default is unset (driver dependent).

fetchSize This is a driver hint that will attempt to cause the
driver to return results in batches of rows numbering
in size equal to this setting. Default is unset (driver
dependent).


statementType Any one of STATEMENT, PREPARED or CALLABLE.
This causes MyBatis to use Statement,
PreparedStatement or CallableStatement
respectively. Default: PREPARED.


resultSetType Any one of FORWARD_ONLY|
SCROLL_SENSITIVE| SCROLL_INSENSITIVE.
Default is unset (driver dependent).

databaseId In case there is a configured databaseIdProvider,
MyBatis will load all statements with no
databaseId attribute or with a databaseId that
matches the current one. If case the same statement
if found with and without the databaseId the latter
will be discarded.

我们挨个讲解一下select的这些属性标签:
id -- 一个命名空间里的唯一标识,你如果动手完成了前面的helloworld,这个没什么难理解的。

parameterType -- 自动映射参数类型,值为一个全类名或者alias别名。
(具体可参照iBatis中讲述的映射参数 http://blog.csdn.net/partner4java/article/details/8175358)
Demo1:简单类型
我们根据用户id查询对应用户信息:
这里的parameterType就为一个int类型
<select id="selectUsernameByID" resultType="string" parameterType="int">
select username from user where id = #{value}
</select>
String username = session.selectOne("user.selectUsernameByID", 1);

Demo2:自定义对象类型
我们查询一条Person数据,它的名字为hello,年龄为23。
<select id="queryPerson" resultType="person" parameterType="person">
select * from person where person_name = #{personName} and age = #{age}
</select>
Person person = new Person();
person.setPersonName("hello");
person.setAge(23);
System.out.println(sqlSession.selectList("person.queryPerson",person));
parameterType="person"我们指定了一个alias别名。

parameterMap -- 自定义参数映射(已过时)
前面parameterType借助了默认的反射机制,我们还可以自己指定各种参数对应关系和类型:
<parameterMap class="account" id="accountMap">
<parameter property="username" nullValue="hello" jdbcType="VARCHAR"/>
<parameter property="password" nullValue="123" jdbcType="VARCHAR"/>
<parameter property="groupname" nullValue="123" jdbcType="EMPLOYEE"/>
</parameterMap>
<select ... parameterMap="accountMap">
</select>

resultType -- 自动映射返回类型,值为一个全类名或者alias别名。
如果数据库返回列名称和POJO名字相对应,就应该直接使用本配置,MyBatis会自动把相匹配的数据塞进我们这里指定的类。
有时我们的类单词分隔符使用的下划线,而POJO是大写字母,我们可以在setting中配置mapUnderscoreToCamelCase(参考“配置详解”)。

resultMap -- 自定义返回映射
用法同parameterMap

cache将在后面章节具体学习。

timeout -- 最大相应时间。

fetchSize -- 
参照JDBC:setFetchSize 最主要是为了减少网络交互次数设计的。访问ResultSet时,如果它每次只从服务器上取一行数据,则会产生大量的开销。setFetchSize的意 思是当调用rs.next时,ResultSet会一次性从服务器上取得多少行数据回来,这样在下次rs.next时,它可以直接从内存中获取出数据而不 需要网络交互,提高了效率。 这个设置可能会被某些JDBC驱动忽略的,而且设置过大也会造成内存的上升。

databaseId -- 结合“配置详解”里的databaseIdProvider

·insert, update and delete
The data modification statements insert, update and delete are very similar in their implementation:
<insert
id="insertAuthor"
parameterType="domain.blog.Author"
flushCache="true"
statementType="PREPARED"
keyProperty=""
keyColumn=""
useGeneratedKeys=""
timeout="20000">
<update
id="insertAuthor"
parameterType="domain.blog.Author"
flushCache="true"
statementType="PREPARED"
timeout="20000">
<delete
id="insertAuthor"
parameterType="domain.blog.Author"
flushCache="true"
statementType="PREPARED"
timeout="20000">


Attribute Description
id A unique identifier in this namespace that can be used
to reference this statement.

parameterType The fully qualified class name or alias for the
parameter that will be passed into this statement.


parameterMap This is a deprecated approach to referencing an
external parameterMap. Use inline parameter
mappings and the parameterType attribute.

flushCache Setting this to true will cause the 2nd level and local
caches to be flushed whenever this statement is
called. Default: true for insert, update and delete
statements.

timeout This sets the maximum time the driver will wait for the
database to return from a request, before throwing an
exception. Default is unset (driver dependent).


statementType Any one of STATEMENT, PREPARED or CALLABLE.
This causes MyBatis to use Statement,
PreparedStatement or CallableStatement
respectively. Default: PREPARED.


useGeneratedKeys (insert only) This tells MyBatis to use the JDBC
getGeneratedKeys method to retrieve keys
generated internally by the database (e.g. auto
increment fields in RDBMS like MySQL or SQL
Server). Default: false


keyProperty (insert only) Identifies a property into which
MyBatis will set the key value returned by
getGeneratedKeys, or by a selectKey child
element of the insert statement. Default: unset.


keyColumn (insert only) Sets the name of the column in the table
with a generated key. This is only required in certain
databases (like PostgreSQL) when the key column is
not the first column in the table.

The following are some examples of insert, update and delete statements.
<insert id="insertAuthor" parameterType="domain.blog.Author">
insert into Author (id,username,password,email,bio)
values (#{id},#{username},#{password},#{email},#{bio})
</insert>
<update id="updateAuthor" parameterType="domain.blog.Author">
update Author set
username = #{username},
password = #{password},
email = #{email},
bio = #{bio}
where id = #{id}
</update>
<delete id="deleteAuthor" parameterType="int">
delete from Author where id = #{id}
</delete>

这些元素的使用和我们select大致相同。
不同的是多了useGeneratedKeys属性标签:
用于在你插入的时候自动生成主键。
作何解释呢?比如你MySQL(支持自动生成主键),做了一条插入:
<insert id="addPerson" parameterType="person">
insert into person (id,person_name,password,age) values (#{id},#{personName},#{pass},#{age})
</insert>
Person person = new Person();
person.setPersonName("hello");
person.setAge(23);
sqlSession.insert("person.addPerson", person);
sqlSession.commit();
System.out.println(person.getId());
执行完,打印id为null。可是,有时候我们想获取id怎么呢?
<insert id="addPerson" parameterType="person" useGeneratedKeys="true" keyProperty="id">
insert into person (id,person_name,password,age) values (#{id},#{personName},#{pass},#{age})
</insert>
首先打开使用getGeneratedKeys -- useGeneratedKeys="true",然后告诉MyBatis哪个是你的主键keyProperty="id"(id为我们POJO主键属性名称)。
当然使用本特性的关键在于驱动程序支持。

MyBatis还对不支持自增长的数据库提供了支持,在insert标签中使用selectKey标签:
MyBatis has another way to deal with key generation for databases that don't support auto-generated
column types, or perhaps don't yet support the JDBC driver support for auto-generated keys.
Here's a simple (silly) example that would generate a random ID (something you'd likely never do,
but this demonstrates the flexibility and how MyBatis really doesn't mind):
<insert id="insertAuthor" parameterType="domain.blog.Author">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1
</selectKey>
insert into Author
(id, username, password, email,bio, favourite_section)
values
(#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouriteSection}
</insert>
In the example above, the selectKey statement would be run first, the Author id property would
be set, and then the insert statement would be called. This gives you a similar behavior to an autogenerated
key in your database without complicating your Java code.
The selectKey element is described as follows:
<selectKey
keyProperty="id"
resultType="int"
order="BEFORE"
statementType="PREPARED">
Attribute Description
--------------------------------------------------------
keyProperty The target property where the result of the
selectKey statement should be set.

resultType The type of the result. MyBatis can usually figure
this out, but it doesn't hurt to add it to be sure.
MyBatis allows any simple type to be used as the key,
including Strings.

order This can be set to BEFORE or AFTER. If set to
BEFORE, then it will select the key first, set the
keyProperty and then execute the insert
statement. If set to AFTER, it runs the insert statement
and then the selectKey statement – which is
common with databases like Oracle that may have
embedded sequence calls inside of insert statements.

statementType Same as above, MyBatis supports STATEMENT,
PREPARED and CALLABLE statement types that
map to Statement, PreparedStatement and
CallableStatement respectively.


·sql
This element can be used to define a reusable fragment of SQL code that can be included in other
statements. For example:
<sql id="userColumns"> id,username,password </sql>


The SQL fragment can then be included in another statement, for example:
<select id="selectUsers" parameterType="int" resultType="hashmap">
select <include refid="userColumns"/>
from some_table
where id = #{id}
</select>


mysql 全文模糊查找 便捷解决方案 php unicode 工具类 博文链接:https://alxw4616.iteye.com/blog/1886618 立即下载

相关推荐

MyBatis中的模糊查询语句

主要介绍了MyBatis中的模糊查询语句的相关资料,需要的朋友可以参考下

mybatis 模糊查询(like和match against两种)

<select id="searchUser" parameterType="java.lang.String" resultType="com.datebook.vo.UserDetailVO"> select id,mobile,header,nickname,gender,birthday,signature,photoes,book_cnt from user where <

停止使用 4310

解决MySQL数据库中文模糊检索问题的方法

在 MySQL下,在进行中文模糊检索时,经常会返回一些与之不相关的记录,如查找 “%a%” 时,返回的可能有中文字符,却没有a字符存在。本人以前也曾遇到过类似问题,经详细阅读MySQL的Manual,发现可以有一种方法很方便的解决并得到满意的结果。   希望通过“标题”对新闻库进行检索,关键字可能包含是中英文,如下SQL语句:   以下为引用的内容:    Code: select id,title,name from achech_com.news where title like ‘%a%’   返回的结果,某些title字段确定带了“a”关键字,而有些则只有中文,但也随之返回在检索结果中

mysql全文搜索案例_MySQL 全文检索 ngram Mybatis(示例代码)

创建全文索引(FullText index)创建表的同时创建全文索引FULLTEXT (name) WITH PARSER ngram通过 alter table 的方式来添加alter table `das`.`staff_base` add fulltext index staff_base_name(`name`) with parser ngram;直接通过create index的方式(...

weixin_39895481的博客 323

使用Linux安装yum报错 E: Unable to correct problems, you have held broken packages.

使用Linux安装yum报错 E: Unable to correct problems, you have held broken packages.

weixin_43205954的博客 2465

高通平台power_supply 框架下添加第三方充电IC的驱动方法

1.power_supply电源框架介绍: power supply framework在kernel/drivers/power/下。内核抽象出来power supply子系统为驱动提供了统一的框架。 功能包括: 1.抽象PSY设备的共性,向用户空间提供统一的API; 2.为底层PSY驱动的编写,提供简单、统一的方式,同时封装并实现公共逻辑。 power supply class位于d...

Change 1万+

Mybatis动态sql语句foreach中拼接正则表达式字符串注意事项

mysql正则表达式及全文索引与mybatis动态sql结合使用方式

小蜜蜂1010的博客 2629

mipi deskew原理理解

何为skew, 从字面意思看是倾斜了,不对齐了;放在mipi的传输中意思就是clock lane和data lane 及data lane与data lane间出现了相位差;一旦出现相位差,大家采样数据时就可能不在同一个节拍上,会出现传输错误。所以就要做deskew,通过做deskew来使得大家重新对齐,在同一个节奏下传输数据. 一般当data rate高于1.5G时建议开启deskew。

lx123010的专栏 8127

《partner4java 讲述MyBatis入门》之第一步:MyBatis HelloWorld

What is MyBatis? MyBatis是一个一流的支持自定义SQL,存储过程和高级映射的持久化框架。 MyBatis隐藏了几乎所有的JDBC代码、参数的手动设置和结果检索。 它通过简单的XML或注解来实现映射器层,所谓映射器层,是用于在对象和数据库之间搬运数据,同时保证对象、数据库以及映射器本身都相互独立。 (MyBatis 本是apache的一个开源项目 iBatis

java相关技术(partner4java专栏)希望对您的学习有所帮助 2193

保姆级教程:用Qlib和LightGBM从零搭建你的第一个AI量化选股策略(附完整代码)

本文提供了一份详细的教程,教你如何使用Qlib和LightGBM从零搭建AI量化选股策略。教程涵盖了环境配置、数据获取、特征工程、模型训练和策略回测等关键步骤,并附有完整代码和常见问题解决方案,适合量化投资初学者快速上手。

weixin_29191081的博客 449

13、基于RBF的自适应鲁棒控制与反步控制方法及实现

本文介绍了基于RBF神经网络的自适应鲁棒控制与反步控制方法,详细阐述了控制系统的程序结构、核心算法及实现流程。通过Simulink搭建仿真系统,利用RBF网络逼近系统中的不确定非线性函数,并结合Lyapunov稳定性理论设计控制律,实现了对倒立摆等复杂非线性系统的高精度跟踪控制。文章还提供了完整的MATLAB/Simulink代码示例和仿真结果分析,验证了该方法的有效性与鲁棒性,为实际工程应用提供了可行的技术路径。

ol789012的博客 96

Mybatis 笔记

一、Mybatis可以获取插入记录的自增长主键ID(程序执行插入操作后返回自增id,作为参数的实体类自动更新) 1.在插入语句<insert>标签中添加属性“useGeneratedKeys”和“keyProperty”,其中keyProperty是Java对象的属性名,而不是数据表的字段名。 1 <insert id="insertPartnerUser...

weixin_30583563的博客 135

具身智能 | 从具身智能出发谈多传感器融合技术

多传感器融合感知是具身智能系统突破“感知—认知—行动”闭环的核心使能技术。本文从具身智能的视角出发,对多传感器融合技术进行系统综述。首先阐述了具身智能对多传感器融合提出的独特需求,包括异构感知集成、跨模态语义对齐和实时闭环决策。其次,构建了多层级融合技术分类框架,从数据层融合、特征层融合、决策层融合、时序融合到多模态大语言模型(MLLM)融合,逐层梳理主流方法与演进脉络。在此基础上,分析了面向具身智能的通用融合架构设计,涵盖了感知—推理—执行三层架构及其关键组件。

尘世冰封的专栏 318

可白嫖源码---课程设计--毕业设计--34120 基于Spring boot的私房菜定制上门服务系统的研究(案例分析)-附源码

技术上,后端采用Java语言与SpringBoot框架构建RESTfulAPI,实现细粒度权限控制与业务逻辑;前端基于Vue.js开发用户界面,提升操作流畅性;数据存储使用MySQL,确保订单、菜品、用户等核心信息的一致性与可追溯性。系统不追求功能繁杂,而是聚焦“看得见流程、信得过服务、用得顺操作”三个实际目标。预期系统上线后可降低个体厨师的数字化门槛,提升用户参与意愿,为社区级餐饮微服务提供一套低成本、易维护、真落地的工具支撑。

vx2_Biye_Design的博客 536

5、数字图像采集:X射线成像技术全解析

本文全面解析了数字图像采集中的X射线成像技术,涵盖数字X射线探测器、荧光透视与血管造影、乳腺摄影以及计算机断层扫描(CT)的图像重建原理。详细介绍了TFT平板探测器的优势、DSA技术在血管成像中的应用、乳腺摄影对高对比度和分辨率的需求,以及CT中基于Radon变换和滤波反投影的重建方法。同时探讨了噪声、部分容积效应、金属伪影和运动伪影等常见问题及其影响。最后总结了各类X射线成像技术的特点与应用场景,并展望了未来在图像质量提升和剂量优化方面的技术发展方向。

l6m7n8的博客 131

VMware系列:此平台不支持虚拟化 Intel-VT-x/EPT 或 AMD-V/RVI

VMware系列:此平台不支持虚拟化 Intel-VT-x/EPT 或 AMD-V/RVI

weixin_54626591的博客 1万+

selectKey标签详解(*)

1.为什么要使用selectKey 数据库主键包括自增和非自增,有时候新增一条数据不仅仅知道成功就行了,后边的逻辑可能还需要这个新增的主键,这时候再查询数据库就有点耗时耗力,我们可以采用selectKey来帮助我们获取新增的主键 2.具体实现demo 查询数据库最简单的几步 (1)controller @Controller public class SelectKeyController { @Autowired SelectKeyServiceImpl selectKeyServic

weixin_42408447的博客 8249

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Mysql全文搜索match against的用法

全文检索在 MySQL 中就是一个 FULLTEXT 类型索引。FULLTEXT 索引用于 MyISAM 表,可以在 CREATE TABLE 时或之后使用 ALTER TABLE 或 CREATE INDEX 在 CHAR、 VARCHAR 或 TEXT 列上创建对于大的数据库,将数据装载到一个没有 FULLTEXT 索引的表中,然后再使用 ALTER TABLE   (或 CREATE IND

yue 4293

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

MyBatis MySQL LIKE 模糊查询优化 全文索引 FULL TEXT 聚合函数COUNT()

LIKE 模糊查询优化 1.使用LOCATE 代替 LIKE 2.使用instr <select id="selectByNameOrAddress" parameterType="java.lang.String" resultMap="BaseResultMap"> select id,name,address,uniform_credit_code,create_...

空 2017

转载一篇: MyBatis 的 Annotations使用案例

Getting Started with iBatis (MyBatis): Annotations Frameworks We Recommend These Resources Java EE &amp; Servlet Containers for ColdFusion Developers Motivations for software ...

jc_dreaming2的博客 331

mybatis常用标签

一.定义sql语句 1.select 标签 属性介绍: (1)id :唯一的标识符. (2)parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User或user (3)resultType :语句返回值类型或别名。注意,如果是集合,那么这里填写的是集合的泛型,而不是集合本身(resultType 与resultMap 不能并用) <select id="selectByPrimaryKey" resultMap="BaseResultMap" parame.

weixin_42408447的博客 1万+

mybatis中的事务处理(commit)

mybatis单独使用时,使用SqlSession来处理事务,打开会话,事务处理开始,增删改操作时要执行commit操作,事物提交后,关闭会话,事物结束。@Test public void insertUserTest() throws Exception { // 1、读取配置文件 String resource = "SqlMapConfig.xml";

xiaolizi22233的博客 1万+

mybatis入门阶段(二)

上一篇文章当中我们已经简单的了解到mybatis的基本概念、如何搭建的思路以及简单创建我的第一个mybatis工程。我们现在在此基础上补充其CRUD以及了解其的生命周期和作用域。

Jackson_Stars的博客 285

【Mybatis】Mybatis学习由浅入深(二)

加载配置信息初始化通过配置文件或注解将配置信息加载成Statement对象接收调用请求接收到请求将请求传递给下层处理处理请求找到对应的Statement对象解析出sql和传入参数获取数据库连接,执行sql,得到执行结果根据配置的映射关系进行转换得到最终的对象结果。释放连接资源处理结果集业务代码得到结果集数据SessionFactory产生的Session关闭。

记录并分享信息的载体 330
上一篇: 《partner4java 讲述MyBatis入门》之第一步:MyBatis HelloWorld
下一篇: 《partner4java 讲述Spring源码》之第一步:Spring IoC
partner4java
博客等级 码龄17年 481粉丝 183原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址