本文目录
- JAVAEE容器怎么管理EntityManager和PersistenceContext
- annotation-config 有什么用
- 为什么我看到spring可以注入抽象类的属性,比如用@PersistenceContext注入EntityManager的对象,用xml呢
- 如何编写自定义存储系统
- 我之前hibernate的session输出都是一串数,这次怎么变成sessionSessionImpl(PersistenceContext[了
- Spring MVC 配置文件讲解
- 关于JavaEE中的EJB容器的理解
- 关于EntityManager的createNativeQuery该怎么处理
- 往DAO类中注入@PersistenceContext和@Resource的区别
- @PersistenceContext 与@Resource(name=“productTypeServiceBean“)两个都是注入啊 有什么区别
JAVAEE容器怎么管理EntityManager和PersistenceContext
容器托管EntityManager @PersistenceContext,存放unitName指向的DataBase对应的EntityBean实例集合,以及对这些实例进行生命周期管理 @PersistenceContext( name=“entityManagerName“, properties=@PersistenceProperty, type=““//PersistenceContextType TRANSACTION (default,transaction-scope)/EXTENDED unitName=““//the persistence unit name) EntityManager 必须关联一个PersistenceContext对象,提供一系列方法对PersistenceContext中的EntityBean实例进行操作。 可以使用依赖注入,将某个PersistenceContext对象注入给EntityManager对象 如: @PersistenceContext(unitName=“lxhPU“) private EntityManager entityManager; JAVAEE容器会智能选取容器中的PersistenceContext实例跟这个entityManager实例来关联 a、一般情况下,一个persistence unit只需对应一个PersistenceContext实例,如 class UserDao{ @PersistenceContext(unitName=“lxhPU“) private EntityManager entityManager; } class OrderDao{ @PersistenceContext(unitName=“lxhPU“) private EntityManager entityManager; } UserDao和OrderDao中的entityManager对象关联的PersistenceContext是同一个实例 当然,我们也可以手动为PersistenceUnit增加PersistenceContext实例 class UserDao{ @PersistenceContext(unitName=“lxhPU“) private EntityManager entityManager; @PersistenceContext(name=“pc2“ ,unitName=“lxhPU“) private EntityManager entityManager2; } UserDao 中的entityManager和entityManager2关联的2个PersistenceContext实例是不同的,尽管他们指向的是同一个PersistenceUnit b、JAVAEE容器会维护PersistenceContext实例及其关联的EntityManger实例 一个PersistenceContext实例可以被多个EntityManager实例关联 class UserDao{ @PersistenceContext(unitName=“lxhPU“) private EntityManager entityManager; @PersistenceContext(unitName=“lxhPU“) private EntityManager entityManager2; } class OrderDao{ @PersistenceContext(unitName=“lxhPU“) private EntityManager entityManager; }
annotation-config 有什么用
它的作用是式地向 Spring 容器注册AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor 以及 RequiredAnnotationBeanPostProcessor 这 4 个BeanPostProcessor。注册这4个 BeanPostProcessor的作用,就是为了系统能够识别相应的注解。例如:如果想使用@Autowired注解,那么就必须事先在 Spring 容器中声明 AutowiredAnnotationBeanPostProcessor Bean。传统声明方式如下:《bean class=“org.springframework.beans.factory.annotation. AutowiredAnnotationBeanPostProcessor “/》 如果想使用@ Resource 、@ PostConstruct、@ PreDestroy等注解就必须声明CommonAnnotationBeanPostProcessor如果想使用@PersistenceContext注解,就必须声明PersistenceAnnotationBeanPostProcessor的Bean。如果想使用 @Required的注解,就必须声明RequiredAnnotationBeanPostProcessor的Bean。同样,传统的声明方式如下:《bean class=“org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor“/》 一般来说,这些注解还是比较常用,尤其是Antowired的注解,在自动注入的时候更是经常使用,所以如果总是需要按照传统的方式一条一条配置显得有些繁琐和没有必要,于是spring给我们提供《context:annotation-config/》的简化配置方式,自动完成声明。使用注解一般都会配置扫描包路径选项《context:component-scan base-package=”XX.XX”/》 该配置项其实也包含了自动注入上述processor的功能,因此当使用 《context:component-scan/》 后,就可以将 《context:annotation-config/》 移除。
为什么我看到spring可以注入抽象类的属性,比如用@PersistenceContext注入EntityManager的对象,用xml呢
关于这个问题,抽象类因为不能实例化,所以不能在spring的xml里配置bean,故不能作为属性注入其他bean。只能用抽象类的完全实现的子类注入。所以楼主不要纠结这个问题。 @PersistenceContext为什么又能实现EntityManager而引入jpa呢? 这是因为spring遇到注解@PersistenceContext后,从容器中得到一个EntityManager对象,但这个对象其实是它子类的对象,而且已经初始化了,不是EntityManager自身的。所有的对象spring都能管理,so,得到一个子类对象很好理解吧
如何编写自定义存储系统
.NET Framework 4.5 包含 SqlWorkflowInstanceStore,使用 SQL Server 保持工作流数据的实例存储。 如果您的应用程序程序需要将工作流数据保存到另一介质,如不同的数据库或文件系统,则您可以实现自定义实例存储。 通过扩展抽象的 InstanceStore 类并实现对实现所需方法来创建自定义实例存储。 使用自定义实例存储 若要实现自定义实例存储,请将实例存储的实例分配到 InstanceStore 并执行 PersistableIdle 方法。 有关具体细节,请参阅 如何:创建和运行长时间运行的工作流 教程。 示例实例存储 下面的代码示例是一个完整的实例存储实现,采取的是 企业采购过程 示例。 此实例存储将工作流数据保存到使用 XML 的文件。 using System; using System.Activities.DurableInstancing; using System.Collections.Generic; using System.IO; using System.Runtime.DurableInstancing; using System.Runtime.Serialization; using System.ServiceModel.Persistence; using System.Xml; using System.Xml.Linq; namespace Microsoft.Samples.WF.PurchaseProcess { public class XmlWorkflowInstanceStore : InstanceStore { Guid ownerInstanceID; public XmlWorkflowInstanceStore() : this(Guid.NewGuid()) { } public XmlWorkflowInstanceStore(Guid id) { ownerInstanceID = id; } //Synchronous version of the Begin/EndTryCommand functions protected override bool TryCommand(InstancePersistenceContext context, InstancePersistenceCommand command, TimeSpan timeout) { return EndTryCommand(BeginTryCommand(context, command, timeout, null, null)); } //The persistence engine will send a variety of commands to the configured InstanceStore, //such as CreateWorkflowOwnerCommand, SaveWorkflowCommand, and LoadWorkflowCommand. //This method is where we will handle those commands protected override IAsyncResult BeginTryCommand(InstancePersistenceContext context, InstancePersistenceCommand command, TimeSpan timeout, AsyncCallback callback, object state) { IDictionary《XName, InstanceValue》 data = null; //The CreateWorkflowOwner command instructs the instance store to create a new instance owner bound to the instanace handle if (command is CreateWorkflowOwnerCommand) { context.BindInstanceOwner(ownerInstanceID, Guid.NewGuid()); } //The SaveWorkflow command instructs the instance store to modify the instance bound to the instance handle or an instance key else if (command is SaveWorkflowCommand) { SaveWorkflowCommand saveCommand = (SaveWorkflowCommand)command; data = saveCommand.InstanceData; Save(data); } //The LoadWorkflow command instructs the instance store to lock and load the instance bound to the identifier in the instance handle else if (command is LoadWorkflowCommand) { string fileName = IOHelper.GetFileName(this.ownerInstanceID); try { using (FileStream inputStream = new FileStream(fileName, FileMode.Open)) { data = LoadInstanceDataFromFile(inputStream); //load the data into the persistence Context context.LoadedInstance(InstanceState.Initialized, data, null, null, null); } } catch (Exception exception) { throw new PersistenceException(exception.Message); } } return new CompletedAsyncResult《bool》(true, callback, state); } protected override bool EndTryCommand(IAsyncResult result) { return CompletedAsyncResult《bool》.End(result); } //Reads data from xml file and creates a dictionary based off of that. IDictionary《XName, InstanceValue》 LoadInstanceDataFromFile(Stream inputStream) { IDictionary《XName, InstanceValue》 data = new Dictionary《XName, InstanceValue》(); NetDataContractSerializer s = new NetDataContractSerializer(); XmlReader rdr = XmlReader.Create(inputStream); XmlDocument doc = new XmlDocument(); doc.Load(rdr); XmlNodeList instances = doc.GetElementsByTagName(“InstanceValue“); foreach (XmlElement instanceElement in instances) { XmlElement keyElement = (XmlElement)instanceElement.SelectSingleNode(“descendant::key“); XName key = (XName)DeserializeObject(s, keyElement); XmlElement valueElement = (XmlElement)instanceElement.SelectSingleNode(“descendant::value“); object value = DeserializeObject(s, valueElement); InstanceValue instVal = new InstanceValue(value); data.Add(key, instVal); } return data; } object DeserializeObject(NetDataContractSerializer serializer, XmlElement element) { object deserializedObject = null; MemoryStream stm = new MemoryStream(); XmlDictionaryWriter wtr = XmlDictionaryWriter.CreateTextWriter(stm); element.WriteContentTo(wtr); wtr.Flush(); stm.Position = 0; deserializedObject = serializer.Deserialize(stm); return deserializedObject; } //Saves the persistence data to an xml file. void Save(IDictionary《XName, InstanceValue》 instanceData) { string fileName = IOHelper.GetFileName(this.ownerInstanceID); XmlDocument doc = new XmlDocument(); doc.LoadXml(“《InstanceValues/》“); foreach (KeyValuePair《XName,InstanceValue》 valPair in instanceData) { XmlElement newInstance = doc.CreateElement(“InstanceValue“); XmlElement newKey = SerializeObject(“key“, valPair.Key, doc); newInstance.AppendChild(newKey); XmlElement newValue = SerializeObject(“value“, valPair.Value.Value, doc); newInstance.AppendChild(newValue); doc.DocumentElement.AppendChild(newInstance); } doc.Save(fileName); } XmlElement SerializeObject(string elementName, object o, XmlDocument doc) { NetDataContractSerializer s = new NetDataContractSerializer(); XmlElement newElement = doc.CreateElement(elementName); MemoryStream stm = new MemoryStream(); s.Serialize(stm, o); stm.Position = 0; StreamReader rdr = new StreamReader(stm); newElement.InnerXml = rdr.ReadToEnd(); return newElement; } } }
我之前hibernate的session输出都是一串数,这次怎么变成sessionSessionImpl(PersistenceContext[了
输出session的是数字,表示的是该session的id,或者hashcode, sessionSessionImpl(PersistenceContext[entityKeys=,collectionKeys=];ActionQueue[insertions= updates= deletions= collectionCreations= collectionRemovals= collectionUpdates=]) 则表示的是对象,内部重写了toString() 方法,输出了该对象内部的一些信息
Spring MVC 配置文件讲解
使用@Controller定义一个控制器 使用@RequestMapping映射请求 使用@RequestParam绑定请求参数到方法参数 使用@ModelAttribute提供一个从模型到数据的链接 使用@SessionAttributes指定存储在会话中的属性《context:annotation-config/》他的作用是隐式地向 Spring 容器注册AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor 这 4 个BeanPostProcessor。例如:如果想使用@ Resource 、@ PostConstruct、@ PreDestroy等注解就必须声明CommonAnnotationBeanPostProcessor。如果想使用@PersistenceContext注解,就必须声明PersistenceAnnotationBeanPostProcessor的Bean。如果你想使用@Autowired注解,那么就必须事先在 Spring 容器中声明 AutowiredAnnotationBeanPostProcessor Bean。传统声明方式如下:《bean class=“org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor “/》 如果想使用 @Required的注解,就必须声明RequiredAnnotationBeanPostProcessor的Bean。同样,传统的声明方式如下:《bean class=“org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor“/》 记得,使用注解一般都会配置扫描包路径选项《context:component-scan base-package=”XX.XX”/》 《servlet》《servlet-name》dispatcherServlet《/servlet-name》《servlet-class》org.springframework.web.servlet.DispatcherServlet《/servlet-class》《init-param》《param-name》contextConfigLocation《/param-name》《param-value》/WEB-INF/dispatcherServlet-servlet.xml《/param-value》《/init-param》《load-on-startup》1《/load-on-startup》《/servlet》《servlet-mapping》《servlet-name》dispatcherServlet《/servlet-name》《url-pattern》*.do《/url-pattern》《/servlet-mapping》这个配置常常见于web.xml文件中《load-on-startup》1《/load-on-startup》是启动顺序,让这个Servlet随Servletp容器一起启动。 《url-pattern》*.do《/url-pattern》 会拦截*.do结尾的请求。《servlet-name》dispatcherServlet《/servlet-name》这个Servlet的名字是dispatcherServlet,可以有多个DispatcherServlet,是通过名字来区分的。每一个DispatcherServlet有自己的WebApplicationContext上下文对象。同时保存的ServletContext中和Request对象中,关于key,以后说明。 在DispatcherServlet的初始化过程中,框架会在web应用的 WEB-INF文件夹下寻找名为[dispatcherServlet]-servlet.xml 的配置文件,生成文件中定义的bean。《init-param》《param-name》contextConfigLocation《/param-name》《param-value》/WEB-INF/dispatcherServlet-servlet.xml《/param-value》《/init-param》指明了配置文件的文件名,不使用默认配置文件名,而使用springMVC.xml配置文件。其中《param-value》**.xml《/param-value》 这里可以使用多种写法1、不写,使用默认值:/WEB-INF/《servlet-name》-servlet.xml2、《param-value》/WEB-INF/classes/springMVC.xml《/param-value》3、《param-value》classpath*:springMVC-mvc.xml《/param-value》4、多个值用逗号分隔springMVC-mvc.xml 配置文件片段讲解《context:annotation-config/》《!-- 自动扫描的包名 --》 《context:component-scan base-package=“com.iflysse“/》 《!-- 默认的注解映射的支持 --》 《mvc:annotation-driven/》《!-- 视图解释类 --》 《bean class=“org.springframework.web.servlet.view.InternalResourceViewResolver“》 《property name=“prefix“ value=“/WEB-INF/jsp/“/》 《property name=“suffix“ value=“.jsp“/》《!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 --》 《property name=“viewClass“ value=“org.springframework.web.servlet.view.JstlView“ /》 《/bean》 《mvc:annotation-driven /》 是一种简写形式,完全可以手动配置替代这种简写形式,简写形式可以让初学都快速应用默认配置方案。《mvc:annotation-driven /》 会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,是spring MVC为@Controllers分发请求所必须的。并提供了:数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)。后面,我们处理响应ajax请求时,就使用到了对json的支持。后面,对action写JUnit单元测试时,要从spring IOC容器中取DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,来完成测试,取的时候要知道是《mvc:annotation-driven /》这一句注册的这两个bean。《!-- json 支持 --》《bean id=“mappingJacksonHttpMessageConverter“class=“org.springframework.http.converter.json.MappingJacksonHttpMessageConverter“》《property name=“objectMapper“ ref=“commonObjectMapper“/》《property name=“supportedMediaTypes“》《list》《value》text/html;charset=UTF-8《/value》《/list》《/property》《/bean》 《!-- ObjectMapper json转换 --》《bean id=“commonObjectMapper“ class=“cn.com.starit.util.CommonObjectMapper“/》
关于JavaEE中的EJB容器的理解
你没有接触过 EJB 2.0 所以有些东西少了些基础。放一个 @EJB 注入资源,本身由服务器自动完成了一些事情,以前 EJB 2.0 的时代我们需要明确的去 RevervationHome home = new InitalContext().lookup(“java:comp/env/ejb/RevervationDAO“) 去拿一个 Home,然后 Reversation service = home.create() 得到一个 Dao 的 EJB 实例(实际上得到的是一个 Stub,你把类名 serivce.getClass().getName() print 出来看一下),因为对于无状态的 session EJB 来说,不需要参数也不需要“开始和结束”的声明,我们没必要每次都手工做,因此 EJB 3.0 开始就让服务器自动帮我们完成这些了,我曾经写一个 EJB 2.0 程序放在服务器上运行,然后写一个 EJB 3.0 的客户端程序来调用 EJB,它能正常工作,也就是说,背后要做的事情并没有少,只是有些步骤自动完成了而已,我们依然可以手工完成这些步骤。我们要知道的是,写了@EJB 并不是直接 new 了一个实例,而是通过 JNDI lookup 得到了一个 Stub 而已。你可以在 IBM 网站上找一个 Hello, World EJB 2.0 样例看,一般文章会先大致说一下开发的过程需要做几件事,然后写段代码来演示一下。光看代码样例的话,很多背景知道是很难从代码中了解到的。我们需要找其它相关的 J2EE 开发基础知道看了才知道。
关于EntityManager的createNativeQuery该怎么处理
Session bean or MD bean对Entity bean的操作(包括所有的query, insert, update, delete操作)都是通过EntityManager实例来完成的。EntityManager是由EJB 容器自动地管理和配置的,不需要用户自己创建。那么Session bean or MD bean如何获得EntityManager实例呢??非常简单,就是通过下列代码进行依赖注入:Public class sessionbean1{@PersistenceContextEntityManager em;。。。}注意:如果persistence.xml文件中配置了多个《persistence-unit》。那么在注入EntityManager对 象时必须指定持久化名称,通过@PersistenceContext注释的unitName属性进行指定,例:@PersistenceContext(unitName=“foshanshop“)EntityManager em;如果只有一个《persistence-unit》,不需要明确指定。请注意:Entity Bean被EntityManager管理时,EntityManager会跟踪他的状态改变,在任何决定更新实体Bean的时候便会把发生改变的值同步 到数据库中(跟hibernate一样)。但是如果entity Bean从EntityManager分离后,他是不受管理的,EntityManager无法跟踪他的任何状态改变。EntityManager一些常用的API(包含query, insert, update, delete操作)1)get entity —— find() or getReference()Person person = em.find(Person.class,1);当在数据库中没有找到记录时,getReference()和find()是有区别的,find()方法会返回null,而getReference() 方法会抛出javax.persistence.EntityNotFoundException例外,另外getReference()方法不保证 entity Bean已被初始化。如果传递进getReference()或find()方法的参数不是实体Bean,都会引发 IllegalArgumentException例外
往DAO类中注入@PersistenceContext和@Resource的区别
@PersistenceContextprivate EntityManager em;注入的是实体管理器,执行持久化操作的,需要配置文件persistence.xml。注入一堆保存实体类状态的数据结构,针对实体类的不同状态(四种,managedh或detached等)可以做出不同的反应(merge,persist等等),其实就是把数据从数据库里提出,然后在内存里处理的,再返回数据库的法则。@Resource是注入容器提供的资源对象,比如SessionContext MessageDrivenContext。或者你那个name指定的JNDI对象可以理解为资源-》数据源-》也就是数据连接,基本上就是告诉程序数据库在哪里
@PersistenceContext 与@Resource(name=“productTypeServiceBean“)两个都是注入啊 有什么区别
@PersistenceContextprivate EntityManager em;注入的是实体管理器,执行持久化操作的,需要配置文件persistence.xml。@Resource是注入容器提供的资源对象,比如SessionContext MessageDrivenContext。或者你那个name指定的JNDI对象