Description

Venkat Krishnan -> http://evenkat.com 1] public interface MessageDestination { void write(String m);} public interface MessageSource {String getTheMessage();} public class SimpleMessageDestination implements MessageDestination { public void write(String m) {System.out.println(m); } } public class SimpleMessageSource implements MessageSource { private String mess; SimpleMessageSource(){ mess="CBIT2"; System.out.println("Constructor called"); } public String getTheMessage() {return mess; } } PropertiesBeanDefinitionReader has the details bean.properties --> src destination.(class)=core.SimpleMessageDestination source.(class)=core.SimpleMessageSource Jar Files: Common Loggings, core, beans public class Main { public static void main(String[] args) { DefaultListableBeanFactory dbf = new DefaultListableBeanFactory(); BeanDefinitionReader dbr = new PropertiesBeanDefinitionReader(dbf); dbr.loadBeanDefinitions(new ClassPathResource("bean.properties")); MessageSource ms=(MessageSource)dbf.getBean("source"); MessageDestination md=(MessageDestination)dbf.getBean("destination"); czxmd.write(ms.getMessage()); System.out.println("Second time"); MessageSource ms1=(MessageSource)dbf.getBean("source"); MessageDestination md1=(MessageDestination)dbf.getBean("destination"); Page 1 of 26 Venkat Krishnan -> http://evenkat.com md1.write(ms1.getMessage()); 2] Adding a service layer to MS and MD 3] Passing values dynamically from the properties file 4] Writing the contents to a file. 5] Show how to use XML as a DD. using XMLBeanFactory and inner beans public interface Oracle { String define();} public interface Encyclo1{Long findLong(String e); } public class DefaultOracle implements Oracle { Encyclo1 enc; public void setEnc(Encyclo1 enc) { this.enc = enc; } public String define() { Long a = enc.findLong("A");Long b = enc.findLong("B");return String.valueOf(a/b); }} public class DefaultEncyclo1 implements Encyclo1 { private Map<String,Long>m = new HashMap<String, Long>(); public DefaultEncyclo1(){ m.put("A", 100L); m.put("B", 10L); } public Long findLong(String e) {return m.get(e);} } public class Main { public static void main(String[] args) { XmlBeanFactory x = new XmlBeanFactory( new ClassPathResource("dynamic.xml")); Oracle o=(Oracle)x.getBean("oracle"); System.out.println(" The new value is "+ o.define()); } <bean id="oracle" class="core.DefaultOracle"> <property name="enc"> <bean class="core.DefaultEncyclo1"/> </property> </bean> </beans> 6] How to pass values from the XML file <bean id="encycl" class="core.DynamicEncyclo"> <constructor-arg> Page 2 of 26 com <util:map> <entry key="A" value="200"/> <entry key="B" value="100"/> </util:map> </constructor-arg> </bean> <bean id="oracle" class="core. @Autowired and ApplicationContext.DefaultOracle"> <property name="enc" ref="encycl"></property> </bean> 7] creating a person interface having the display function and then creating a programmer class having String name. float height. 9] Over Loading the Constructors 10] @Service. Long ageinseconds. boolean javaProgrammer. Have setter methods in this class and override the display function to print the values of the variables. For injecting a value the use of setter does not work if @Service is used Page 3 of 26 .Venkat Krishnan -> http://evenkat. 8] create a DotnetProgrammer class having String name. int age. int experience and boolean advanceConcepts which implements the person interface and initiaze the class variables with a Constructor and DO NOT have setter methods here. springframework.} @Service class DefaultWriter implements IWriter{ public void write(String s){System.com interface IWriter{ void write(String s).println(s).} }} public class Main{ public static void main(String s[]){ ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"). x.execute("Hi"). IWriter writ1.org/schema/contex t" <context:component-scan base-package="core"/> 11] Autowire by Name --> The bean id name should be the same as the name of the property and the setter method should also have the same name 12] Autowire by Type --> The bean id name. property name and the setter method names can all be different Page 4 of 26 . @Autowired public void setWriter(IWriter i){writ = i.out.Venkat Krishnan -> http://evenkat. MySpringInject x = (MySpringInject)ctx. }} beans.write(s).getBean("mySpringInject").xml xmlns:context="http://www.} } @Service public class MySpringInject{ IWriter writ.} public void execute(String s){writ. EmpDao"> --> will not work <bean id = "dao" class="core.println("Test").EmpManager" <property name="dao" ref="empdao"/> <bean id = "empdao" class="core.me2().EmpDao"> 2] <bean id="manager" class = "core.EmpDao"> --> will work 3] <bean id = "empmanager" class="core.} } class Main{ PSVM{ EmpManager v = (EmpManager)ctx. --> setter public void met2(){dao.} } class EmpManager{ EmpDao dao. }} beans.EmpManager" autowire="byName"> <bean id = "empdao" class="core.com 12] Autowire by Constructor -> to be used when one Object should be created and ready when another one is created like Student should be ready when College object is created class EmpDao{ public void met1(){System.Venkat Krishnan -> http://evenkat. --> setter Page 5 of 26 . v.xml 1] <bean id="manager"class = "core.getBean("manager").EmpManager" autowire="byType"> 13] Bean Inheritance public class PersonBase { protected String fname.out.met1(). getBean("padd") PersonSalary ps = (PersonSalary) ctx.a) if the bean has abstract as true can we use getBean on that?[no] b) Should there be extends in java file and parent attributes is there in the bean file for another bean [yes] c) if a bean is abstract. PersonSalary and PersonAddress and pass the property values as defined in java a) How to specify relationship between objects in Bean file. should the java class should be abstract? [no] d) if a java class is abstract should there be abstract attribute in the bean tag? [yes] 14] Bean LifeCycle abstract class Product --> name and price Page 6 of 26 . }} public class PersonAddress extends PersonBase { private String zipcode.getBean("psal").com protected String lname. lname and zipcode public class PersonSalary extends PersonBase{ int salary. --> setter method Have a toString which prints fname. lname and salary public class Main{ PersonAddress pa = (PersonAddress)ctx.Venkat Krishnan -> http://evenkat. [parent attribute="id of the bean"] a. Sop -> pa and ps In the XML file create a bean for PersonBase. --> setter public String toString() { return "PersonBase [fname=" + fname + ". lname=" + lname + "]". --> setter method Have a toString which prints fname. parseDouble(p.ShoppingCart> <bean id = ca class = "core.addItem(p3). ca.addItem(p2).sc.com class Battery extends Product --> toString "Battery "name.checkout(sc). } method-->checkout(ShoppingCart sc){ double total=0.write(new Date()+" = "+ total+"\n").} } class ShoppingCart --> List<Product> items = new ArrayList --> addItem(Product p) { items.true))). price class Disk extends Product --> toString "Disk" name. Product p2 = ac.close(). } w. price class Cashier --> name and path + BufferedWriter w setter methods for name and path method--> openFile(){ File f = new File(path. for (Product p : sc.Battery"> -->name and price (property) <bean id = cd class = "core. ShoppingCart sc = Cashier ca = sc.addItem(p1).Venkat Krishnan -> http://evenkat. Page 7 of 26 . w = new BufferedWriter (new OutputStreamWriter(new FileOutputStream(f. w.txt").getBean("cd"). Product p3 = ac. SOP("Called").Disk"> -->name and price (property) <bean id = dvd class = "core.getBean("a").getPrice()).flush().add(p)} --> List getItems { return items.Cashier"> name and path(property) Main Product p1 = ac.name+".getItems()){ total += Double.sc.disk"> -->name and price (property) <bean id = sc class="core.} XML <bean id = a class = "core.getBean("dvd"). method --> close(){w. properties file write cas.org/schema/context http://www.cashier"> <property name="path" value="${cas.path=c:\ Page 8 of 26 .springframework.org/schema/conte xt"> <xsi:schemaLocation=" http://www.Venkat Krishnan -> http://evenkat. InitializingBean and over ride the methods and in afterPropertiesSet method call openFile c) the destroy method is not by default since the container is not shut down and we can forcefully call it by using AbstractApplicationContext class method called registerShutdownHook() d) use @PreDestroy and @PostConstruct before the methods which performs initialization and destruction and write <xmlns:context="http://www. NullPointer Exception b) implements DisposableBean.getItems().springframework. <bean id="cashier" class="core. How many products should be show for the second user? e.xsd " <context:annotation-config/> e) Create two more products using getBean after the checkout to simulate a different user.org/schema/context/springcontext.com a) Get an error on w.path}"/> <context:property-placeholder location="config. Create one more ShoppingCart Object using getBean and add the 2 products to the new Shopping Cart and then call sc.springframework.properties" /> config.1) How to do the same for annotation? f) Write total amount to a properties file and the location of the directory should be dynamic. long b) --> String getOperationName().setTarget(a).springsource.print().org. pf.addAdvice(new BeforeAdvice()).out. @Before <aop:aspectj-autoproxy> interface Operation --> long operate(long a.))") public void logMethod(JoinPoint jp){ SOP ("AOP Loggin " + jp.Venkat Krishnan -> http://evenkat. cglib jar files AOP public class AdvisedObject { void print(){System. 16] Example showing Annotation @Aspect. class OperationMultiply implements Operation --> operate (return a * b). }} Main Page 9 of 26 . pf.aopalliance-1.println("Hello").b).operate(a. a1. Object arg2) throws Throwable { System.*. AdvisedObject a1 = (AdvisedObject)pf.toShortString()). int b){op. aop jar.0.println("Testing").com 15] com.0. System.. }} class Calculate{ Operation op.out.operate(.getProxy(). --> setter void execute(int a. op.getName()). }} public static void main(String[] args) { AdvisedObject a = new AdvisedObject().out. ProxyFactory pf = new ProxyFactory().getOperationName().} } public class BeforeAdvice implements MethodBeforeAdvice { public void before(Method arg0.println(arg0. Object[] arg1. --> getOperationName ( return "multiply") @Aspect class Logging Aspect{ @Before ("execution(* core. getSignature().equals(methodname)){ return "Wow this is new in Around Advice" } else if("getAround". args[1]).getName().equals(methodname)){ return 50L. c. beans.*. Object op = jp.xml <context:annotation-config> or component-scan <bean id ="opn" class="core.com Calculate c= (Calculate)ac.} } Main class getBean and then call b1 (Basic) all 3 methods XML File--> <bean id="basicimpl" class> <bean id="basicaspect" class> <aop:config><aop:aspect ref="basicaspect"> <aop:pointcut id="pc1" expression= "execution(* core.. if("getBefore". Long getAround(String s) class BasicImpl implements Basic getAfter--> SOP getBefore --> SOP return s getAround --> SOP return 20L class BasicAspect public void beforeMethod(){SOP} public void afterMethod(){SOP} public Object aroundMethod(ProceedingJoinPoint jp){ sop("In Around advice").getBean("calculate").Calculate"> either --> <property> or autowire="byType" <aop:aspectj-autoproxy> <bean id="log" class="core.))"> <aop:before pointcut-ref="pc1" method="beforeMethod"/></aop:pointcut> Page 10 of 26 .OperationMultiply"> <bean id ="cal" class="core.proceed().Venkat Krishnan -> http://evenkat. String methodname = jp.execute(args[0].getBefore(.LogginAspect"/> 17] interface Basic void getAfter(). String getBefore(String s). jsp--><%response.xml --> no change b) redirect.Venkat Krishnan -> http://evenkat.HelloController"> <property name="message" value="welcome to spring MVC"></property> </bean> Redirect.println("In Controller"). Form Tags using Form Tags a) web.*. 19] show the usage of FormController.out. return new ModelAndView("View1".getAfter(.xml Page 11 of 26 .%> Controller --> Insider handleRequestInternal System.springframework.sendRedirect("start."priyanka".jsp --> registeruser.com variations 1] <aop:pointcut id="pc2" expression= "execution(* core.htm c) core-servlet.InternalResource ViewResolver"> <property name="prefix" value="/WEBINF/output/"></property> <property name="suffix" value=".))"> <aop:around pointcut-ref="pc3" method="aroundMethod"/> WSDL [Web Service Description Language] UDDI [Universal Discovery Description Interchange] SOAP [Simple object access protocol] XML 18] Sample MVC Program <bean id="viewResolver" class="org.web.htm" class="core..))"> <aop:before pointcut-ref="pc2" method="afterMethod"/> 2] <aop:pointcut id="pc3" expression= "execution(* core.htm").message).servlet.view..*.jsp"></property> </bean> <bean name="/start.getAround(. com <bean id="viewResolver"--> same <bean name="/userregister. return new ModelAndView("success"."key".springframework.name} your password is ${key. String password.password} f) input. gender.Venkat Krishnan -> http://evenkat.. } public ModelAndView onSubmit(Object p) throws Exception{ User u = (User)p.persist().jsp Your name is ${key.u). country.jsp <%@taglib uri="http://www. --> setter public UserController(){ setCommandClass(User.class).. us.htm" class="core.UserController"> <property name="formView" value="input"/> --> GUI form <property name="successView" value="success"/> <property name="us" ref="uservice"/> </bean> <bean id="uservice" class="core..UserService"/> c1) class User --> String name. String [] community --> getter and setter methods d) class UserController extends SimpleFormController{ UserService us.org/tags/form" prefix="f"%> <!DOCTYPE. setCommandName("POJO").> <html><body> <f:form method="post" commandName="POJO"> <pre> UserName: <f:input path="name"> password: <f:password path="password"> Gender: <f:radiobutton path="gender" value="Male" label="Male"> <f:radiobutton path="gender" value="Female" label="Female"> country:<f:select path="country"> Page 12 of 26 . }} e) success. aboutYou. Errors err){ ValidationUtils. User u1 = (User) p.Venkat Krishnan -> http://evenkat."na me.req"). }} c) core-servlet. if(u1."pas s.class. } private static final int MIN_LEN=6.xml Page 13 of 26 . ValidationUtils.error{color:red."pass.getPassword().rejectValue("password"."password".rejectIfEmptyOrWhitespace(err.length<MIN_LEN){ err. public void validate(Object p.len").req").isAssignableFrom(class). font-style:italic.jsp <head> <style type="text/css"> . } </style></head><body><f:form method="post" commandName="POJO"> UserName: <f:input path="username"> <f:errors path=username cssClass="error"/> b) class UserValidator implements Validator --> override the supports method{ return User.com <f:option value="0" label="India"/><f:option value="1" label="USA"/><f:option value="2" label="UK"/> </f:select> About You<f:textarea path="aboutYou"> Community<f:checkbox path="community" value="Spring" label="Spring"> <input type=submit> g) interface UserService --> persist() h) class UserServiceImpl extends UserService persist (){SOP} 20]validation a) UserForm.rejectIfEmptyOrWhitespace(err."username". GET) String showUserForm(ModelMap m){ User u = new User().htm" class="core. return "input". } @RequestMapping(method=RequestMethod. @RequestMapping(method=RequestMethod. }//end of showOnSubmit Page 14 of 26 .properties name.len=Minimum Number of char is 6 21] Spring Form tags using Annotations a) web.UserController"> <property name="formView" value="input"/> --> GUI form <property name="successView" value="success"/> <property name="us" ref="uservice"/> <property name="validator" ref="uvalidator"/> </bean> <bean id="messageSource" --> page 153> <property name="basename" value="error"/> d) error.htm") @SessionAttributes("user") class User Controller { @Autowired private UserService us.return "success".xml <context:component-scan base-package="core"/> <bean id="viewResolver" /> c) redirect. u. m.addAttribute(u).persist(u).com <bean id="uvalidator" class="core.UserValidator"> <bean name="/userregister.htm d) @Controller @RequestMapping(value="/userannotation.xml file b) core-servlet.POST) public String showOnSubmit(@ModelAttribute("user") User u)throws Exception { us.req=Name is Mandatory pass.jsp --> userannotation.req=Password is required pass.Venkat Krishnan -> http://evenkat.setUserName("Temp"). GET) public string finalTest(){ SOP ("Called"). This annotation is at attribute level and it works in conjuction with Spring's form:form or spring:bind tags in the page. The @ModelAttribute applied on the method level would also be available for the handler methods (as parameters using @ModelAttribute on parameters).com }//end of Controller Variation of refresh on the final page a) in the POST Handler method return "redirect:any. in a way they are request scoped.htm". method=RequestMethod. for example when you submit a form and a validation error occurs and you are taken back to the same form. @SessionAttribute is used on a form lifecycle handling controller to specify which of the model attributes are to be bound to the session (so that they can be retrieved in subsequent requests that still concern the same controller. All the parameters and methods(return values) annotated with @ModelAttribute would be added to the model object to be used by the views for rendering the output. return "usersuccess". If you want any of these modelattributes to be added/retrieved to/from the session. So. then annotate the class with @SessionAttributes(modelattributename) Page 15 of 26 .htm" b) Create another controller called @Controller class UserSuccessController{ @RequestMapping(value="/any. with all the inputs you entered properly preserved. } } With @ModelAttribute.Venkat Krishnan -> http://evenkat. you specify that an attribute you are passing to / receiving from a controller's method is "bound" to an attribute of your model. br).xml JAR FILES REQUIRED: SECURITY CONFIG.springframework.htm".web. /WEB-INF/springsecurity.xml.hasErrors()){return "userForm".springframework.ContextLoaderListener </listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/mvc-dispatcher-servlet.validate(u.context. use @Autowired above the constructor to do the injection c) In the onSubmit method define the second parameter called BindingResult br.xml </param-value> </context-param> <filter> <filter-name>springSecurityFilterChain</filter-name> <filterclass>org.Venkat Krishnan -> http://evenkat. }else {return "redirect:usersuccess. d) in the body of onSubmit call the validate function and check for hasErrors of the br object with a if-else userValidator. CORE AND WEB <listener> <listenerclass>org.web.} 23] Spring Security a) web.com 22] Spring Validation using Annotations a) In the UserController class define UserValidator as a class variable.DelegatingFilterProxy</filt er-class> Page 16 of 26 . if(br.filter. b) Define a constructor to UserController which takes UserService and UserValidator in its parameters and assigns the value to the class variable. }} 24] Spring JDBC transaction and jdbc jar files + database specific jar file 1] beans. return "hello".Venkat Krishnan -> http://evenkat.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@localhost:1521:XE" ></property> Page 17 of 26 .springframework.xml <bean id="ds" class="org. "Spring Security hello").addAttribute("message".xml <http auto-config="true"> <intercept-url pattern="/welcome*" access="ROLE_USER" /> </http> <authentication-manager> <authentication-provider> <user-service> <user name="abc" password="123" authorities="ROLE_USER" /> </user-service> </authentication-provider> </authentication-manager> </beans:beans> c) Controller file @Controller @RequestMapping(value="/welcome") public class HelloController { @RequestMapping(method = RequestMethod.datasource.com </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> b)spring-security.DriverManagerDat aSource"> <property name="driverClassName" value="oracle.jdbc.jdbc.GET) public String printWelcome(ModelMap model) { model. new StudentMapper()). s1. s1.?)".getInt("id")). 3] create a StudentDAO Interface public interface StudentDao { void setDataSource(DataSource ds). } public void create(String name.getString("name")).NEXTVAL. Integer age) { String sql = "INSERT INTO STUDENT VALUES(SEQUENCEID.Venkat Krishnan -> http://evenkat. s1. Integer age).query(q. List<Student> s=jt.setId(rs. int row = jt.update(sql.getInt("age")).setAge(rs. List<Student> listStudents().?. private JdbcTemplate jt. int r) throws SQLException { Student s1 = new Student().StudentJdbcTemplate"> <property name="dataSource" ref="ds" /> </bean> 2] Create a Student POJO having sid as the primary key and name and age as attributes. name.com <property name="username" value="system" /> <property name="password" value="admin" /> </bean> <bean id="stujdbc" class="core. return s. } 5] Create a Custom Mapper public class StudentMapper implements RowMapper<Student> { public Student mapRow(ResultSet rs. } 4] Create a implementation: public class StudentJdbcTemplate implements StudentDao { private DataSource ds. Page 18 of 26 . public void setDataSource(DataSource ds) { this. Sop("Student created"). Have getter and setter methods for all 3 and override toString to display all 3 attributes.setName(rs. void create(String name.ds = ds. jt = new JdbcTemplate(ds). } public List<Student> listStudents() { String q="SELECT * FROM STUDENT". age). StudentJdbcTemplate s1=(StudentJdbcTemplate)apx. }} 6] Create the Main ApplicationContext apx = new ClassPathXmlApplicationContext("beans. s1. Integer id).url connection.xml .password connection.Page 7 hibernate-configuration connection.hibernate.OracleDialect</property> Page 19 of 26 . s1.driver_class connection.create("Anand". List<Student> l=s1.create("Ruksar".listStudents().pool_size 10 dialect">org.xml"). -----------------------------------------------CREATE SEQUENCE SEQUENCEID MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE 10.com return s1. void delete(Integer id).getBean("stujdbc"). void updateAge(Integer age. System. Main make the necessary changes ================================================ ===== Spring Core AOP Spring MVC Spring Security Spring JDBC .cfg.out.Venkat Krishnan -> http://evenkat.CRUD 25] a) hibernate.dialect. 24).username connection.println(l).22). -----------------------------------------------Variation:Student getStudent(Integer id). c. c.commit().ses. String lname and Getter and Setter methods d) HibernateUtil-copy it from Java Persistence book. ses. ses. ses.xml --> generator to native c) Course Pojo -> courseid and coursename d) HibernateUtil e) Main methods --> Integer saveCourse(String name) --> listCourse() --> updateCourse(Integer id.auto">create</property> <mapping resource="Contact.openSession().close(). f) jar file hibernate3.xml --> hbm2ddl to update b) Course.setId(1). c.hbm. Session ses =sf.getSessionFactory(). String fname.cfg.hbm.getTransaction().shutdown(). page 91 e) Main PSVM--> SessionFactory sf = HibernateUtil.flush().setLname("B"). String name) --> deleteCourse(Integer id) Page 20 of 26 .Venkat Krishnan -> http://evenkat. Contact c = new Contact().save(c).com show_sql">true</property> hbm2ddl.Contact" table="CONTACTS"> <id name="id" type="integer" column="contactid"> <generator class="assigned"/> </id> <property name="fname" column = "ContactFName"/> <property name="lname" column = "ContactLName"/> </class> </hibernate-mapping> c) class Contact with Integer id.xml <!DOCTYPE page 66> <hibernate-mapping> <class name="core.jar + all jars in required and JPA folder 26] CRUD .xml"/> </session-factory> </hibernate-configuration> b) Contact. ses.setFname("A").hbm.beginTransaction().Course Example a) hibernate.HibernateUtil. saveCourse("Physics"). private String partyName.* org. } updateCourse(Integer i. sop(cc.deleteCourse(x1).i).updateCourse(x2.persistence. for (Iterator i = li.cfg. } deleteCourse(Integer i){ Course c2 = (Course)ses. listCourse(){ List li=ses. m.setCoursename(n). Integer x2 = m.get(Course. Integer x1 = m. m.list(). String n){ Course c1 = (Course)ses.listCourse().getCourseName()).* @Entity @Table(name="OrderDetails") public class Order{ private int oid.Venkat Krishnan -> http://evenkat.iterator.Order javax.xml --> <mapping class="core.saveCourse("Biology").get(Course.next().Order"/> b) POJO . ses.listCourse().class.hibernate. i. c1.class.com PSVM Main m = new Main(). Integer x3 = m. } 27] a) Hibernate.createQuery("from Course"). @Id @GeneratedValue @Column(name="order_id") public int getOid(){} @Column(name="Party_Name") Page 21 of 26 . m."Chemistry").){ Course cc = (Course)i.saveCourse("Maths").hasNext().delete(c2).i). m. ses. Address sAddress @Column(name="Student_Name". nullable=false. String state c) Main Address a1 = new Address("Mumbai".College table="CollegeDetails"> <id name="c_id" type column> <generator > <property name="college_name" type="String" column> <property name="college_address"> Page 22 of 26 .com public String getPartyName(){} write setter methods } c) HibernateUtil d) Main insert 2 orders 28] One-To-One using Annotation [Student --> Address] a) Student Integer sid. Student s1 = new Student("ABC". length=100) public String getSName() @OneToOne(cascade=CascadeType.Venkat Krishnan -> http://evenkat. Student s2 = new Student("XYZ".xml --> <mapping resource="College.save(s2)."WB").ALL) public Address getAddress b) Address Integer aid. String sName.a2).xml"> Course also b) College."MAH").hbm.xml <h-m> <class name=core.a1). ses. Address a2 = new Address("Kol".hbm.save(s1). 29] Many to One using XML file College-->1 Course--N c_id cs_id college_name course_name college_address course_category college_course --> 1 a) cfg. String city. College e) POJO .Course cs_id.save(c1).cfg.College f) Main College c = new College(). constructor with sname and a set @Id @GeneratedValue @Column public Integer getSid(){} setSid @Column public String getSname() Page 23 of 26 . String sname Set<Phone> sphone = new HashSet<Phone>(). course_category.Venkat Krishnan -> http://evenkat.xml <h-m> <class> <id> <property name="course_name"> <property name="course_category"> <many-to-one name="college_course" class="core. Course c1 = pass c Course c2 = pass c ses. ses. course_name.College" cascade="all" not-null="true"/? </class> d) POJO . 30] One to Many using Annotation One Student having multiple Phones sid pid sname ptype pname Student_Phone Table sid pid a) hibernate.xml --> mapping class b) Student --> POJO @Entity @Table(name="StudentPhone") public class Student{ Integer sid.save(c2).com </class></h-m> c) Course.hbm. hibernate.com setSname() @OneToMany(cascade=CascadeType. keep generator to assigned in one.hibernate. In one to Many do not create 2 students 31] Many to Many using XML file with Student and Course NOTE: Please use setID and manually set the values for Course. } b] In Hibernate.xml <property name="hibernate.ALL) PageNo 159 @JoinTable(name="Student_Phone". ses.annotations.Cache.Venkat Krishnan -> http://evenkat. joinColumns=( @JoinColumn(name="sid")). inverseJoinColumns=(@JoinColumn (name="pid")) ) public Set<Phone> getSphone() setSphone(). pnos.CacheConcurrencyStrategy.add(new Phone) pnos. private String userName.pnos). import org.cache. c) Phone -> POJO d) Main Set<Phone> pnos = new HashSet<Phone>(). @Entity @Cacheable @Cache(usage=CacheConcurrencyStrategy.cfg. 32] Caching Techniques a] Session Cache: import org.READ_ONL Y)// no writing of userdetails in to DB public class UserDetails { @Id @GeneratedValue private int userId.add(new Phone) Student s1 = new Student("ABC".annotations.use_second_level_cache">true</prope rty> Page 24 of 26 .save(s1). configure().openSession().setUserName("XYZ").getUserName()+" u1 ").out.out.buildSessionFactory().out. Session sess2 = sf1.get(UserDetails.class.E hCacheProvider</property> --> make hbm2dll to create [just making it easy] c] In Main UserDetails u = new UserDetails().cache. System.get(UserDetails.class.cache. u1.println(" u3 "+u4.getUserName()+" u1 "). Page 25 of 26 .save(u).t. ses.com <property name="hibernate.use_query_cache">true</property> SessionFactory sf = new Configuration().1).class. System.getUserName()). [variation2] <property name="hibernate. 6). Session sess = sf.getSessionFactory.ses. [variation1] Session sess1 = sf.out. Query q = sess.println(u1. System. UserDetails u3 = (UserDetails)sess1.close().cache.provider_class">org.println(u2.get(UserDetails.println(" u3 "+u3.get(UserDetails.class.1). SessionFactory sf1 = new Configuration().commit(). u. System. UserDetails u4 = (UserDetails)sess2.createQuery("from UserDetails u where u.out. UserDetails u2=(UserDetails) ses. UserDetails u1=(UserDetails) ses.getUserName()).openSession().buildSessionFactory().configure(). If you are using HibernateUtil.println("-----------------------"). System.Venkat Krishnan -> http://evenkat.setUserName("ABC").userId = 5").it will have only 1 select statement. 6).hibernate.openSession(). setCacheable(true).size()).openSession().out. [email protected] Page 26 of 26 . Query q6 = sess6.Venkat Krishnan -> http://evenkat. q6. System.userId =5").println(l1.close().com q. Session sess6 = sf.list(). sess.createQuery("from UserDetails u where u. System.size()). sess6. List l2 = q6.setCacheable(true).close().list().println(l2. List l1 = q.out.
Copyright © 2024 DOKUMEN.SITE Inc.