Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Che Delilas
Nov 23, 2009
FREE TIBET WEED

nakieon posted:

I... wow. That is a great post. I read this 3 days ago and something just felt off about it.

Less than a minute ago I just realized you structured your last sentence in the ternary operator pattern: boolean ? expression1 : expression2

Amazing.

Thanks, I have my moments.

Adbot
ADBOT LOVES YOU

Guildenstern Mother
Mar 31, 2010

Why walk when you can ride?
My superpower is getting bean creation errors every time I so much as look directly at my code. Had to recreate the whole drat project because the main package just was not picking up on any of the packages below it. V2 for some reason doesn't have this problem despite all the code being the same. Everything was working fine until I added a new repository and now I'm getting poo poo like



quote:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'appController': Invalid autowire-marked constructor: public com.alder.locpol.controller.AppController(com.alder.locpol.repository.BBRepository). Found constructor with 'required' Autowired annotation already: public com.alder.locpol.controller.AppController(com.alder.locpol.repository.UserRepository)


repository:

code:
package com.alder.locpol.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.alder.locpol.model.BoardBill;


@Repository
	public interface BBRepository extends JpaRepository <BoardBill, String>{

	}

controller:

code:
@RestController
@RequestMapping("/")
@CrossOrigin
public class AppController {
	
	private UserRepository userRepository;
	private BBRepository bbRepository;
	
	@Autowired
	public AppController(UserRepository userRepository) {
		super();
		this.userRepository = userRepository;
	}
	@Autowired
	public AppController(BBRepository bbRepository) {
		super();
		this.bbRepository = bbRepository;
	}

Guildenstern Mother fucked around with this message at 23:00 on Sep 8, 2020

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.
Why does your controller have two separate constructors like that? Don't you just want to have one constructor accepting both repositories as arguments? Why are you calling super? Finally, if you only have one constructor you can leave out the autowired annotation.

Guildenstern Mother
Mar 31, 2010

Why walk when you can ride?
Honestly I'm really new and I knew the first one worked so I kind of assumed I should do the second one the same. Its the first project I've done with springboot outside of an in class lab. I'll go dig through some old code and see if I can't figure out what it should look like and why.


edit: I changed it, broke it again, and finally realized I had a wrong import on my @Id.

Guildenstern Mother fucked around with this message at 23:06 on Sep 8, 2020

Eezee
Apr 3, 2011

My double chin turned out to be a huge cyst
Your constructor should look like this:

code:
public AppController(BBRepository bbRepository, UserRepository userRepository) {
	this.bbRepository = bbRepository;
	this.userRepository = userRepository;
	}
I'm assuming your controller needs both the BBRepository and the Userrepository, so you should make sure that both are set in the constructor. If you set your dependencier to "private final" your IDE will give you proper hints if do it something wrong and unless you absolutely need to change dependencies at runtime that should be the standard.
Also you do not need the @Autowired annotation for constructor injection.

Guildenstern Mother
Mar 31, 2010

Why walk when you can ride?
Thanks, I was totally unaware you could just tack them together like that. Can you explain a bit more about when I should and shouldn't autowire repositories? Its a thing our lecturers have always had us make a point of doing, but if its bad practice I don't want to keep doing it unnecessarily.

Objective Action
Jun 10, 2007



Guildenstern Mother posted:

Thanks, I was totally unaware you could just tack them together like that. Can you explain a bit more about when I should and shouldn't autowire repositories? Its a thing our lecturers have always had us make a point of doing, but if its bad practice I don't want to keep doing it unnecessarily.

This is going to sound really mean but I promise I am trying in good faith to help you from a place of bitter and hard won experience.

You have some fundamental misunderstandings about how this all works.

The good news is this is not uncommon at all, especially with frameworks. It sounds like your instructor has started you guys out with Spring Boot to try and make it easy to do really complicated stuff under the hood (like have a REST service) without needing to think about the guts too hard at the start. This is good and fine but if you are fundamentally confused about how the basics of the language and the framework work you are going to be miserable the second something doesn't work correctly or you want to do something outside the pale for the framework.

Fundamentally the current problem you have makes more sense if you step back and think of this as just a class and Spring as another person. What you have is a class you can build in two ways. It can either be a class to do things with a BBRepository (B) or a class to do things with a UserRepository (U) (there are other problems with that but lets ignore that for now). What you have done by making them both marked @Autowired is asked Spring "Can you make a class that does things with an A, then make that same thing at the same time with a B?" when you meant to ask "Can you make a class that has an A and a B". The first sentence makes no sense at all and the second one makes perfect sense.

What Spring was trying to report there is a common problem with all frameworks, it doesn't have context to give you a good human readable error that explains that exactly because from its perspective that kind of error can show up in all sorts of situations. This is a good example of why having some inkling of how the magic works is so important to making solving problems much less frustrating.

What Spring's injection library is telling you there is "Hey wait, you gave me two ways to make this class. I can do that but since you can only call one constructor in Java you need to tell me which one gets priority". In this case you have a class that has no default constructor, neither of the @Autowired ones have any other context to break a tie, and so Spring either has to guess (bad!) or give you an error (better!). You could absolutely have a class like this that works as a BBRepository frobulator when you launch the application as a client and a UserRepository munger when you are running as a server. To do that you would need some way to know and tell Spring which to use. There are approximately a million ways but just think of it as a theoretical annotation you add in addition to @Autowired, lets call it @Conditional, so you make one as @Conditional(class=Foo.class) and the other @Conditional(class=Bar.class). Then Spring would look at what classes are in the classpath and if it sees one but not the other it knows how to break the tie.

This is a bad idea and bad practice; but you could!

As for your actual question you don't have to annotate the constructor @Autowired in modern Spring but I would recommend doing so anyway (or use the more generic @Inject) just to mentally keep it straight as to what is happening. There are a lot of people that will crow about how to use or not use dependency injection but there are pros and cons to everything. Generally you want to be taking advantage of your dependency injection wherever you can because it encourages breaking things up and making them more modular. My personal preference is to use constructor injection only and never use setter or field based annotations. This lets you throw away, change, or sidestep the DI setup you have and still make your classes by hand with fewer headaches. This also tends to make it easier to deal with testing those classes in unit tests.

The best thing you can do is step back and read some documentation on how Spring Boot is doing what its doing at a rough high level. Spring is a giant bundle of a lot of other styles of programming, libraries, and sub-frameworks so to narrow down the reading you probably want to just look at the documentation for dependency injection in general and Spring's implementation specifically. This will be boring. It is absolutely worth it.

Objective Action fucked around with this message at 14:16 on Sep 9, 2020

Guildenstern Mother
Mar 31, 2010

Why walk when you can ride?
Thanks, that wasn't mean at all actually. I am 100% sure I have many other fundamental misconceptions, so getting one of them out of the way is a good step forward. You're right about how they got us started on Spring, lots of "here's a lab that will have useful code to look back at later NOW MOVING ON". Bootcamp go fast. Hopefully I'll wrap this project up in time and have time during the initial job search process to fill up these giant gaps in my understanding. At least before the tech interviews start.

F_Shit_Fitzgerald
Feb 2, 2017



I'm a C++ guy who wants to relearn Java. I've barely touched it since I took a community college course years ago (2008). Is there a good site, ideally not a pay one, where I can re-teach myself Java? Nearly every coding job I've ever seen requires Java and sticking with C++ is probably hurting me in the job market.

RandomBlue
Dec 30, 2012

hay guys!


Biscuit Hider

F_Shit_Fitzgerald posted:

I'm a C++ guy who wants to relearn Java. I've barely touched it since I took a community college course years ago (2008). Is there a good site, ideally not a pay one, where I can re-teach myself Java? Nearly every coding job I've ever seen requires Java and sticking with C++ is probably hurting me in the job market.

https://www.baeldung.com/java-tutorial

Lots of good, free tutorials on Java and Spring there.

F_Shit_Fitzgerald
Feb 2, 2017



RandomBlue posted:

https://www.baeldung.com/java-tutorial

Lots of good, free tutorials on Java and Spring there.

Great! Thank you. I need to use this time to bolster my coding skills.

Manager Hoyden
Mar 5, 2020

Speaking of learning Java, I really need some instruction carrying me from intermediate to real-world-actual-development skills. Is there anything like that out there? Basically getting over the hump from theory to real-world practice.

I am an old (kinda) who took the condescending advice and is learning to code, but I'm getting nervous about my level of knowledge. I have learned a ton of concepts, but I have no drat idea how to put them together to do anything useful and I don't see my last few classes remaining in the degree changing that level of knowledge much.

This is like learning the theory of how like 50% of the parts of a car work but nothing about how a whole car works. And also the parts I learned about mostly aren't even used in the real world anymore. And from there I'm supposed to know how to design and build a car.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Manager Hoyden posted:

Speaking of learning Java, I really need some instruction carrying me from intermediate to real-world-actual-development skills. Is there anything like that out there? Basically getting over the hump from theory to real-world practice.

I am an old (kinda) who took the condescending advice and is learning to code, but I'm getting nervous about my level of knowledge. I have learned a ton of concepts, but I have no drat idea how to put them together to do anything useful and I don't see my last few classes remaining in the degree changing that level of knowledge much.

This is like learning the theory of how like 50% of the parts of a car work but nothing about how a whole car works. And also the parts I learned about mostly aren't even used in the real world anymore. And from there I'm supposed to know how to design and build a car.

Build & ship something. It doesn't necessarily have to be a new idea that people are going to use, but building & shipping something really helps drives home all the theory. Instagram / Twitter clone, simple message board, etc. Use an issue tracker to help plan out your work, and write useful commit messages that have the ticket number in them which you are addressing. Buy a domain and hosting and get it out there with a demo people can click through. That is the sort of thing that would impress me during an interview.

quote:

And also the parts I learned about mostly aren't even used in the real world anymore

Can you elaborate a bit on that part?

Objective Action
Jun 10, 2007



It might not be quite as hands on as what you are looking for but I will always take time to shill for Joshua Bloch's Effective Java as a good overall handbook.

From there what I would do is go to GitHub's trending page and sort by Java and find 2-3 projects that are interesting and spend some time building them in your IDE of choice and poking around. It might not be the cleanest or most well put together code but its likely to be way more informative about real world conditions you are likely to see in the wild. Make sure its a project that does something you are personally interested in! If you pick the most popular thing you will just burn out before you learn anything useful looking at the code.

Love Stole the Day
Nov 4, 2012
Please give me free quality professional advice so I can be a baby about it and insult you
Also this: https://github.com/search?l=Java&q=comments%3A%3E3+label%3Ahelp-wanted+state%3Aopen&type=Issues

Sort by "most comments" to see what the most visible and high profile ones that you could help with are

Hippie Hedgehog
Feb 19, 2007

Ever cuddled a hedgehog?
While I applaud the initiative to give help to open-source projects that need it, maybe it's not the best entry point for a beginner. Most of the questions on that list will be pretty complicated tasks where the maintainers/authors are either out of their depth or don't know which direction to go. Not much a newbie can contribute to those.

I agree with the "build something" advice. Something non-trivial but which is deployed in a modern way using whatever framework strikes your fancy. For example, if class has only taught you to write unix-like command-line applications, go ahead and dive into a simple web-app framework like Javalin and build a simple frontend in React (or whatever you prefer). Write a file sharing service, or something else that requires user account handling and several layers or architecture but is not too large in scope.

Twerk from Home
Jan 17, 2009

This avatar brought to you by the 'save our dead gay forums' foundation.

Manager Hoyden posted:

Speaking of learning Java, I really need some instruction carrying me from intermediate to real-world-actual-development skills. Is there anything like that out there? Basically getting over the hump from theory to real-world practice.

I am an old (kinda) who took the condescending advice and is learning to code, but I'm getting nervous about my level of knowledge. I have learned a ton of concepts, but I have no drat idea how to put them together to do anything useful and I don't see my last few classes remaining in the degree changing that level of knowledge much.

This is like learning the theory of how like 50% of the parts of a car work but nothing about how a whole car works. And also the parts I learned about mostly aren't even used in the real world anymore. And from there I'm supposed to know how to design and build a car.

If you want, I've got a bunch of tiny applications I made for fun that I'd be willing to give you access to source, I could even suggest some features to implement. For example, https://www.tromd.com/ displays horrifying photos of the president, random and new every time you reload.

i vomit kittens
Apr 25, 2019


I'm having a hard time understanding what the purpose of the "Containing" term is in Spring Hibernate/JPA repositories is. I'm using Postgres if that makes a difference. I have a Role entity that contains two different list attributes, one of them being a list of User objects who have that role and another being a list of Strings that make up the permissions that role has, like this (it's Kotlin but same thing):

code:
@Entity
class Role(
        var name: String,
        @JsonIgnore @ManyToOne var organization: Organization,
        @JsonIgnore @ManyToMany var users: MutableList<User>,
        @ElementCollection var permissions: MutableList<String>
) : BaseEntity<Long>()
When I first made the repository for this, I wanted to be able to search with a user to figure out what role they have or search with a specific permission to find roles that have that permission, so I defined it like so:

code:
interface RoleRepository : JpaRepository<Role, Long> {

    fun findAllByOrganization(organization: Organization): List<Role>
    fun findByOrganizationAndUsersContaining(organization: Organization, user: User): Role
    fun findByOrganizationAndPermissionsContaining(organization: Organization, permission: String): List<Role>
}
When I started testing this though, only the findByOrganizationAndUsersContaining function worked, findByOrganizationAndPermissionsContaining always returned an empty list. I eventually found out that if I simply changed the latter function to remove the word "Containing" it worked as expected. For the hell of it, I removed it from the Organization/User find and that also worked just as well.

I'm not very good at straight SQL, but reading through the documentation/StackOverflow I can't figure out why this is. I understand that an Element Collection isn't stored the same way as a Many to Many relationship, but why is it that "Containing" seems to make no difference when querying actual entities while it can't be used at all for an Element Collection?

i vomit kittens fucked around with this message at 00:28 on Oct 21, 2020

CPColin
Sep 9, 2003

Big ol' smile.
I don't know the answer, but your post inspired me to make this:

Only registered members can see post attachments!

Coco13
Jun 6, 2004

My advice to you is to start drinking heavily.
My current programming course is Java-flavored, and this is the first time my Python background is tripping me up. The project is to take each word in a text file and keep track of what "page" it shows up on. I want to create a dictionary or hashmap where the key is the word and the value is a set of the page numbers, but I'm getting tripped up on how to access the set. Any pointers on how to make it happen, or am I on the wrong train of thought to begin with?

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Coco13 posted:

My current programming course is Java-flavored, and this is the first time my Python background is tripping me up. The project is to take each word in a text file and keep track of what "page" it shows up on. I want to create a dictionary or hashmap where the key is the word and the value is a set of the page numbers, but I'm getting tripped up on how to access the set. Any pointers on how to make it happen, or am I on the wrong train of thought to begin with?

I'm assuming you have something like Map<String, Set<Integer>> wordPages ? You get the set with the map's get() method, then you can check membership with contains(), get an array of members with toArray(), or iterate using the iterator.

code:
Map<String, Set<Integer>> wordPages = new HashMap<String, Set<Integer>>();

// populate your map of sets

// Then, you can access like this
Set<Integer> pages = wordPages.get(word);
boolean firstPage = pages.contains(1);

Iterator<Integer> iter = pages.iterator();
while (iter.hasNext()) {
    System.out.println(iter.next());
}

// or just get the contents as an array
Integer[] pageNumbers = pages.toArray(new Integer[pages.size()]);
Here's the doc on a HashSet, the likely implementation of set you're using:
https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html

1337JiveTurkey
Feb 17, 2005

You probably want to use TreeMap and TreeSet instead of HashMap and HashSet if the goal is to display things in order.

Soricidus
Oct 21, 2010
freedom-hating statist shill

carry on then posted:

I'm assuming you have something like Map<String, Set<Integer>> wordPages ? You get the set with the map's get() method, then you can check membership with contains(), get an array of members with toArray(), or iterate using the iterator.

code:
Map<String, Set<Integer>> wordPages = new HashMap<String, Set<Integer>>();

// populate your map of sets

// Then, you can access like this
Set<Integer> pages = wordPages.get(word);
boolean firstPage = pages.contains(1);

Iterator<Integer> iter = pages.iterator();
while (iter.hasNext()) {
    System.out.println(iter.next());
}

// or just get the contents as an array
Integer[] pageNumbers = pages.toArray(new Integer[pages.size()]);
Here's the doc on a HashSet, the likely implementation of set you're using:
https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html

Wow serious old school java there, it’s been years since I saw anyone use a raw iterator when they didn’t want to call remove(), or wrote out the full generic type on both sides of an assignment

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE
yeah idiomatic way to iterate Iterables these days is to use for(MyType obj : iterableCollection) { }, unless you need to remove an object you're iterating from the set, where you do need to touch the iterator

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Soricidus posted:

Wow serious old school java there, it’s been years since I saw anyone use a raw iterator when they didn’t want to call remove(), or wrote out the full generic type on both sides of an assignment

I deal with some very old school customers who keep using Java 6, and work with the XML classes which aren't Iterable at all, so you're lucky I didn't get the array and do an index for.

carry on then fucked around with this message at 20:12 on Oct 27, 2020

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

I also like how the Java thread is 99% nitpicking.

e: now that I have some time, if we want to get fully modern Java:

code:
var wordPages = new TreeMap<String, Set<Integer>>();

// populate your map of sets

// Then, you can access like this
Set<Integer> pages = wordPages.get(word);
boolean firstPage = pages.contains(1);

pages.stream().forEach(System.out::println);

// or just get the contents as an array
var pageNumbers = pages.toArray(new Integer[pages.size()]);
but you're looking at at least Java 11 required to run that.

carry on then fucked around with this message at 22:25 on Oct 27, 2020

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Just use a SortedSetMultimap.

RandomBlue
Dec 30, 2012

hay guys!


Biscuit Hider

carry on then posted:

I also like how the Java thread is 99% nitpicking.

e: now that I have some time, if we want to get fully modern Java:

code:
var wordPages = new TreeMap<String, Set<Integer>>();

// populate your map of sets

// Then, you can access like this
Set<Integer> pages = wordPages.get(word);
boolean firstPage = pages.contains(1);

pages.stream().forEach(System.out::println);

// or just get the contents as an array
var pageNumbers = pages.toArray(new Integer[pages.size()]);
but you're looking at at least Java 11 required to run that.

That looks like basic Java 8 to me (doh missed the vars but come on), that introduced streams a long time ago and if you're just going to do:

code:
pages.stream().forEach(System.out::println);
then this would be simpler and faster:

code:
pages.forEach(System.out::println);
and a good IDE will tell you to change it to this because it's the same thing but usually faster:

code:
for (Integer page : pages) {
    System.out.println(page);
}
I hope this was sufficiently nitpicky and I can't wait to see 12 errors pointed out in my 4 lines of code.

e: Guess it's good that I'm so used to var now that I don't even notice it when reading code now.

RandomBlue fucked around with this message at 03:28 on Oct 28, 2020

Objective Action
Jun 10, 2007



gently caress var forever. Take that poo poo back to Scala nerds!

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

I hope that student learned never to ask questions in the Java thread ever again because this was the opposite of helpful.

RandomBlue
Dec 30, 2012

hay guys!


Biscuit Hider

carry on then posted:

I hope that student learned never to ask questions in the Java thread ever again because this was the opposite of helpful.

:same:

RandomBlue fucked around with this message at 06:39 on Oct 28, 2020

RandomBlue
Dec 30, 2012

hay guys!


Biscuit Hider

Objective Action posted:

gently caress var forever. Take that poo poo back to Scala nerds!

Strongly typed local variable type inference is actually good most of the time unless you like repeating yourself on the same line:

OmgType varName = new OmgType();

BabyFur Denny
Mar 18, 2003

RandomBlue posted:

Strongly typed local variable type inference is actually good most of the time unless you like repeating yourself on the same line:

OmgType varName = new OmgType();

I kinda like that after typing

BeanFactory beanFactory = new BeanFactory();

even the most junior programmer will know what object this is. Not a lot of room for confusion.

And it's not like you have to type it out, the IDE will autocomplete like 80% of that line

i vomit kittens
Apr 25, 2019


RandomBlue posted:

Strongly typed local variable type inference is actually good most of the time unless you like repeating yourself on the same line:

OmgType varName = new OmgType();

this is part of the reason why I like Kotlin so much. while it's technically never required to give the type of your variables, IntelliJ will yell at you to do so except in cases where the answer is incredibly obvious from looking at the other side of the equal sign. i don't program in any professional capacity but I can't imagine ever choosing to use plain old Java again when given the option

Objective Action
Jun 10, 2007



RandomBlue posted:

Strongly typed local variable type inference is actually good most of the time unless you like repeating yourself on the same line:

OmgType varName = new OmgType();

As someone who has spent literal weeks of my life digging through other peoples code to figure out which undocumented type was being injected and which of the seven interfaces happened to be used at the moment the library was being called: we are going to have to agree to disagree on this one.

Here is a nice Scala example that took fifteen minutes of my life yesterday:
code:
val filterFuncs = filters.map(filter => createFilterFunction(filter))
Strongly-typed right? So just ask the compiler or IDE!

Nope, that unrolls into six layers of three different interfaces and four traits. Time to slap a logpoint or debugger onto your code like some kind of goddamn caveman.

RandomBlue
Dec 30, 2012

hay guys!


Biscuit Hider

Objective Action posted:

Here is a nice Scala example that took fifteen minutes of my life yesterday:
code:
val filterFuncs = filters.map(filter => createFilterFunction(filter))
Strongly-typed right? So just ask the compiler or IDE!

Nope, that unrolls into six layers of three different interfaces and four traits. Time to slap a logpoint or debugger onto your code like some kind of goddamn caveman.

I agree that there are times like your example where you shouldn't use var. Any time the return type is non-obvious you shouldn't use it.

RandomBlue fucked around with this message at 15:16 on Oct 28, 2020

barkbell
Apr 14, 2006

woof
java sucks but it pays

rujasu
Dec 19, 2013

RandomBlue posted:

I agree that there are times like your example where you shouldn't use var. Any time the return type is non-obvious you shouldn't use it.

You know what is even easier than that? Never using var. Then you don't have to think about whether it is OK to use var.

Objective Action
Jun 10, 2007



I'm not trying to dogpile on you or anyone specifically but this whole concept of "less to type" being important to people still baffles me a little. I spend maybe 10% of my time typing in code and 90% reading code, thinking about what I want to do, and how I want to do it.

Being easy to write is less important to me than being easy to read and digest what the hell a piece of code is doing. I have this argument with people constantly about things like APL where every bit of code ever produced for that is effectively write-once.

Adbot
ADBOT LOVES YOU

chippy
Aug 16, 2006

OK I DON'T GET IT
I've always kind of missed var coming from C# (didn't realise we had it now, my workplace is currently still stuck on Java 8), but it was very useful in conjunction with LINQ where you work with anonymous types a lot, or aren't always sure which of a certain set of interfaces you might get an instance of from a particular query (but didn't care, because you were probably just iterate over it or call .ToList() on it anyway).

It can make code more or less readable depending on where it's used, so requires a little thought, but that does tend to become automatic after a while.

chippy fucked around with this message at 17:45 on Oct 28, 2020

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply